Bug 1595319 - enable eslint for mail/extensions/openpgp. r=mkmelin
authorKai Engert <kaie@kuix.de>
Thu, 20 Feb 2020 16:37:31 +0100
changeset 28821 e3303808c5963389b113110f07773ba1343e6e0f
parent 28820 59fc6dacc978d7a7ed090927f311f845b78084a4
child 28822 507970329f68e3d3214d3e31a825dd52eda8d77e
push id17055
push userkaie@kuix.de
push dateSat, 22 Feb 2020 11:56:24 +0000
treeherdercomm-central@6c75755a02eb [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmkmelin
bugs1595319
Bug 1595319 - enable eslint for mail/extensions/openpgp. r=mkmelin Differential Revision: https://phabricator.services.mozilla.com/D63493
.eslintignore
mail/extensions/openpgp/content/BondOpenPGP.jsm
mail/extensions/openpgp/content/am-enigprefs.xhtml
mail/extensions/openpgp/content/modules/addrbook.jsm
mail/extensions/openpgp/content/modules/amPrefsService.jsm
mail/extensions/openpgp/content/modules/app.jsm
mail/extensions/openpgp/content/modules/armor.jsm
mail/extensions/openpgp/content/modules/attachment.jsm
mail/extensions/openpgp/content/modules/autoSetup.jsm
mail/extensions/openpgp/content/modules/autocrypt.jsm
mail/extensions/openpgp/content/modules/clipboard.jsm
mail/extensions/openpgp/content/modules/commandLine.jsm
mail/extensions/openpgp/content/modules/compat.jsm
mail/extensions/openpgp/content/modules/configBackup.jsm
mail/extensions/openpgp/content/modules/configure.jsm
mail/extensions/openpgp/content/modules/constants.jsm
mail/extensions/openpgp/content/modules/core.jsm
mail/extensions/openpgp/content/modules/cryptoAPI.jsm
mail/extensions/openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm
mail/extensions/openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm
mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-key.jsm
mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm
mail/extensions/openpgp/content/modules/cryptoAPI/interface.js
mail/extensions/openpgp/content/modules/data.jsm
mail/extensions/openpgp/content/modules/decryption.jsm
mail/extensions/openpgp/content/modules/dialog.jsm
mail/extensions/openpgp/content/modules/encryption.jsm
mail/extensions/openpgp/content/modules/errorHandling.jsm
mail/extensions/openpgp/content/modules/events.jsm
mail/extensions/openpgp/content/modules/files.jsm
mail/extensions/openpgp/content/modules/filters.jsm
mail/extensions/openpgp/content/modules/filtersWrapper.jsm
mail/extensions/openpgp/content/modules/fixExchangeMsg.jsm
mail/extensions/openpgp/content/modules/funcs.jsm
mail/extensions/openpgp/content/modules/glodaUtils.jsm
mail/extensions/openpgp/content/modules/gpg.jsm
mail/extensions/openpgp/content/modules/hash.jsm
mail/extensions/openpgp/content/modules/httpProxy.jsm
mail/extensions/openpgp/content/modules/key.jsm
mail/extensions/openpgp/content/modules/keyObj.jsm
mail/extensions/openpgp/content/modules/keyRefreshService.jsm
mail/extensions/openpgp/content/modules/keyRing.jsm
mail/extensions/openpgp/content/modules/keyUsability.jsm
mail/extensions/openpgp/content/modules/keyserver.jsm
mail/extensions/openpgp/content/modules/keyserverUris.jsm
mail/extensions/openpgp/content/modules/lazy.jsm
mail/extensions/openpgp/content/modules/locale.jsm
mail/extensions/openpgp/content/modules/localizeHtml.jsm
mail/extensions/openpgp/content/modules/log.jsm
mail/extensions/openpgp/content/modules/masterpass.jsm
mail/extensions/openpgp/content/modules/mime.jsm
mail/extensions/openpgp/content/modules/mimeDecrypt.jsm
mail/extensions/openpgp/content/modules/mimeEncrypt.jsm
mail/extensions/openpgp/content/modules/mimeVerify.jsm
mail/extensions/openpgp/content/modules/msgRead.jsm
mail/extensions/openpgp/content/modules/openpgp.jsm
mail/extensions/openpgp/content/modules/os.jsm
mail/extensions/openpgp/content/modules/passwordCheck.jsm
mail/extensions/openpgp/content/modules/persistentCrypto.jsm
mail/extensions/openpgp/content/modules/pgpmimeHandler.jsm
mail/extensions/openpgp/content/modules/pipeConsole.jsm
mail/extensions/openpgp/content/modules/prefs.jsm
mail/extensions/openpgp/content/modules/protocolHandler.jsm
mail/extensions/openpgp/content/modules/rng.jsm
mail/extensions/openpgp/content/modules/rnp.jsm
mail/extensions/openpgp/content/modules/rnpLib.jsm
mail/extensions/openpgp/content/modules/rules.jsm
mail/extensions/openpgp/content/modules/searchCallback.jsm
mail/extensions/openpgp/content/modules/send.jsm
mail/extensions/openpgp/content/modules/singletons.jsm
mail/extensions/openpgp/content/modules/socks5Proxy.jsm
mail/extensions/openpgp/content/modules/sqliteDb.jsm
mail/extensions/openpgp/content/modules/stdlib.jsm
mail/extensions/openpgp/content/modules/stdlib/compose.jsm
mail/extensions/openpgp/content/modules/stdlib/misc.jsm
mail/extensions/openpgp/content/modules/stdlib/msgHdrUtils.jsm
mail/extensions/openpgp/content/modules/streams.jsm
mail/extensions/openpgp/content/modules/time.jsm
mail/extensions/openpgp/content/modules/timer.jsm
mail/extensions/openpgp/content/modules/trust.jsm
mail/extensions/openpgp/content/modules/uris.jsm
mail/extensions/openpgp/content/modules/verify.jsm
mail/extensions/openpgp/content/modules/versioning.jsm
mail/extensions/openpgp/content/modules/webKey.jsm
mail/extensions/openpgp/content/modules/windows.jsm
mail/extensions/openpgp/content/modules/wkdLookup.jsm
mail/extensions/openpgp/content/modules/wksMimeHandler.jsm
mail/extensions/openpgp/content/modules/xhrUtils.jsm
mail/extensions/openpgp/content/modules/zbase32.jsm
mail/extensions/openpgp/content/strings/enigmail.properties
mail/extensions/openpgp/content/ui/am-enigprefs.js
mail/extensions/openpgp/content/ui/commonWorkflows.js
mail/extensions/openpgp/content/ui/enigmailCommon.js
mail/extensions/openpgp/content/ui/enigmailEditIdentity.js
mail/extensions/openpgp/content/ui/enigmailKeyImportInfo.js
mail/extensions/openpgp/content/ui/enigmailKeyManager.js
mail/extensions/openpgp/content/ui/enigmailKeySelection.js
mail/extensions/openpgp/content/ui/enigmailKeygen.js
mail/extensions/openpgp/content/ui/enigmailMessengerOverlay.js
mail/extensions/openpgp/content/ui/enigmailMsgBox.js
mail/extensions/openpgp/content/ui/enigmailMsgComposeHelper.js
mail/extensions/openpgp/content/ui/enigmailMsgComposeOverlay.js
mail/extensions/openpgp/content/ui/enigmailMsgHdrViewOverlay.js
mail/extensions/openpgp/content/ui/keyDetailsDlg.js
--- a/.eslintignore
+++ b/.eslintignore
@@ -72,26 +72,24 @@ mail/app/profile/channel-prefs.js
 mail/base/content/protovis-r2.6-modded.js
 mail/branding/nightly/thunderbird-branding.js
 mail/branding/thunderbird/thunderbird-branding.js
 # This file is split into two in order to keep it as a valid json file
 # for documentation purposes (policies.json) but to be accessed by the
 # code as a .jsm (schema.jsm)
 mail/components/enterprisepolicies/schemas/schema.jsm
 mail/components/im/all-im.js
+mail/extensions/openpgp/prefs/openpgp-prefs.js
 mail/locales/en-US/all-l10n.js
 mail/components/compose/texzilla/**
 mail/components/compose/composer.js
 
 # exclude MailConstants.jsm because: #filter subtitution
 mail/base/modules/MailConstants.jsm
 
-# openpgp exclusions, should get enabled, tracked in bug 1595319
-mail/extensions/openpgp/**
-
 # calendar/ exclusions
 
 # prefs files
 calendar/lightning/content/lightning.js
 calendar/providers/gdata/defaults/preferences.js
 calendar/timezones/preferences.js
 
 # third party library
--- a/mail/extensions/openpgp/content/BondOpenPGP.jsm
+++ b/mail/extensions/openpgp/content/BondOpenPGP.jsm
@@ -33,18 +33,16 @@ const getEnigmailPgpmimeHander = Enigmai
   "EnigmailPgpmimeHander"
 );
 const getRNP = EnigmailLazy.loader("enigmail/rnp.jsm", "RNP");
 const getEnigmailWindows = EnigmailLazy.loader(
   "enigmail/windows.jsm",
   "EnigmailWindows"
 );
 
-/* global APP_SHUTDOWN: false */
-
 var BondOpenPGP = {
   logException(exc) {
     try {
       Services.console.logStringMessage(exc.toString() + "\n" + exc.stack);
     } catch (x) {}
   },
 
   initDone: false,
--- a/mail/extensions/openpgp/content/am-enigprefs.xhtml
+++ b/mail/extensions/openpgp/content/am-enigprefs.xhtml
@@ -130,18 +130,16 @@
 
                 <checkbox id="openpgp.sendKeyWithMsg"
                             label="&enigmail.amPrefPgp.sendKeyWithMsg.label;"
                             checked="false"/>
               </vbox>
 
               <!-- Autocrypt tab -->
               <vbox flex="1" align="start">
-                <html:p id="enigmail_amPrefAutocryptDesc" onclick="Enigmail.edit.handleClick(event)"></html:p>
-
                 <checkbox id="enigmail_enableAutocrypt"
                     prefstring="mail.server.%serverkey%.enableAutocrypt"
                     preftype="bool" prefattribute="value"
                     observes="enigmail_bcEnablePgp"
                     oncommand="Enigmail.edit.enableAcSettings()"
                     label="&enigmail.enableAutocrypt.label;"/>
 
                 <checkbox id="enigmail_acPreferEncrypt"
--- a/mail/extensions/openpgp/content/modules/addrbook.jsm
+++ b/mail/extensions/openpgp/content/modules/addrbook.jsm
@@ -1,50 +1,46 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailAddrbook"];
 
 /*
  * Functionality related to the Thunderbird address book
  *
  */
 
-
-
-
-
 const ABMANAGER = "@mozilla.org/abmanager;1";
 
 var EnigmailAddrbook = {
   /**
    * Look up the address book card for a given email address
    *
    * @param emailAddr: String - email address to find
    *
    * @return if found: Object:
    *           - card: nsIAbCard for found email address
    *           - directory: nsIAbDirectory of found card
    *         NULL if not found
    */
-  lookupEmailAddress: function(emailAddr) {
+  lookupEmailAddress(emailAddr) {
     let abm = Cc[ABMANAGER].getService(Ci.nsIAbManager);
 
     for (let abd of abm.directories) {
       try {
         let crd = abd.cardForEmailAddress(emailAddr);
-        if (crd) return {
-          directory: abd,
-          card: crd
-        };
-      }
-      catch (x) {}
+        if (crd) {
+          return {
+            directory: abd,
+            card: crd,
+          };
+        }
+      } catch (x) {}
     }
 
     return null;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/amPrefsService.jsm
+++ b/mail/extensions/openpgp/content/modules/amPrefsService.jsm
@@ -1,73 +1,74 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
-const {
-  manager: Cm,
-  results: Cr,
-  Constructor: CC
-} = Components;
+const { manager: Cm } = Components;
 Cm.QueryInterface(Ci.nsIComponentRegistrar);
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 const CATEGORY = "mailnews-accountmanager-extensions";
 const CATEGORY_ENTRY = "openpgp-account-manager-extension";
-const PREF_SERVICE_NAME = "@mozilla.org/accountmanager/extension;1?name=enigprefs";
+const PREF_SERVICE_NAME =
+  "@mozilla.org/accountmanager/extension;1?name=enigprefs";
 
 var EXPORTED_SYMBOLS = ["EnigmailAmPrefsService"];
 
 var EnigmailAmPrefsService = {
-  startup: function(reason) {
+  startup(reason) {
     try {
-      var catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
-      catMan.addCategoryEntry(CATEGORY,
+      Services.catMan.addCategoryEntry(
+        CATEGORY,
         CATEGORY_ENTRY,
         PREF_SERVICE_NAME,
-        false, true);
+        false,
+        true
+      );
       this.factory = new Factory(EnigmailPrefService);
-    }
-    catch (ex) {}
+    } catch (ex) {}
   },
 
-  shutdown: function(reason) {
-    var catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
-    catMan.deleteCategoryEntry(CATEGORY, CATEGORY_ENTRY, false);
+  shutdown(reason) {
+    Services.catMan.deleteCategoryEntry(CATEGORY, CATEGORY_ENTRY, false);
 
     if (this.factory) {
       this.factory.unregister();
     }
-  }
+  },
 };
 
 function EnigmailPrefService() {}
 
 EnigmailPrefService.prototype = {
   name: "enigprefs",
   chromePackageName: "openpgp",
   classID: Components.ID("{f2be6d32-ff3c-11e9-8e8b-00163e5e6c00}"),
   classDescription: "OpenPGP Account Manager Extension Service",
   contractID: PREF_SERVICE_NAME,
   QueryInterface: EnigmailCompat.generateQI(["nsIMsgAccountManagerExtension"]),
 
-  showPanel: function(server) {
+  showPanel(server) {
     // show Enigmail panel for POP3, IMAP, NNTP and "movemail" (unix) account types
     switch (server.type) {
       case "nntp":
       case "imap":
       case "pop3":
       case "movemail":
         return true;
     }
     return false;
-  }
+  },
 };
 
 class Factory {
   constructor(component) {
     this.component = component;
     this.register();
     Object.freeze(this);
   }
@@ -75,18 +76,20 @@ class Factory {
   createInstance(outer, iid) {
     if (outer) {
       throw Cr.NS_ERROR_NO_AGGREGATION;
     }
     return new this.component();
   }
 
   register() {
-    Cm.registerFactory(this.component.prototype.classID,
+    Cm.registerFactory(
+      this.component.prototype.classID,
       this.component.prototype.classDescription,
       this.component.prototype.contractID,
-      this);
+      this
+    );
   }
 
   unregister() {
     Cm.unregisterFactory(this.component.prototype.classID, this);
   }
 }
--- a/mail/extensions/openpgp/content/modules/app.jsm
+++ b/mail/extensions/openpgp/content/modules/app.jsm
@@ -3,69 +3,71 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailApp"];
 
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const getEnigmailLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const DIR_SERV_CONTRACTID = "@mozilla.org/file/directory_service;1";
-const ENIG_EXTENSION_GUID = "{847b3a00-7ab1-11d4-8f02-006008948af5}";
-const XPCOM_APPINFO = "@mozilla.org/xre/app-info;1";
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const getEnigmailLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
 
 var EnigmailApp = {
   /**
    * Platform application name (e.g. Thunderbird)
    */
-  getName: function() {
-    return Cc[XPCOM_APPINFO].getService(Ci.nsIXULAppInfo).name;
+  getName() {
+    return Services.appinfo.name;
   },
 
   /**
    * Platform (Gecko) version number (e.g. 42.0)
    * The platform version for SeaMonkey and for Thunderbird are identical
    * (unlike the application version numbers)
    */
-  getPlatformVersion: function() {
-    return Cc[XPCOM_APPINFO].getService(Ci.nsIXULAppInfo).platformVersion;
+  getPlatformVersion() {
+    return Services.appinfo.platformVersion;
   },
 
   /**
    * Return the directory holding the current profile as nsIFile object
    */
-  getProfileDirectory: function() {
-    let ds = Cc[DIR_SERV_CONTRACTID].getService(Ci.nsIProperties);
-    return ds.get("ProfD", Ci.nsIFile);
+  getProfileDirectory() {
+    return Services.dirsvc.get("ProfD", Ci.nsIFile);
   },
 
   /**
    * Get Enigmail version
    */
-  getVersion: function() {
+  getVersion() {
     getEnigmailLog().DEBUG("app.jsm: getVersion\n");
-    getEnigmailLog().DEBUG("app.jsm: installed version: " + EnigmailApp._version + "\n");
+    getEnigmailLog().DEBUG(
+      "app.jsm: installed version: " + EnigmailApp._version + "\n"
+    );
     return EnigmailApp._version;
   },
 
   /**
    * Get Enigmail installation directory
    */
-  getInstallLocation: function() {
+  getInstallLocation() {
     return EnigmailApp._installLocation;
   },
 
-  setVersion: function(version) {
+  setVersion(version) {
     EnigmailApp._version = version;
   },
 
-  setInstallLocation: function(location) {
+  setInstallLocation(location) {
     EnigmailApp._installLocation = location;
   },
 
-  initAddon: function() {
+  initAddon() {
     EnigmailApp.setVersion(0);
     EnigmailApp.setInstallLocation(0);
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/armor.jsm
+++ b/mail/extensions/openpgp/content/modules/armor.jsm
@@ -1,22 +1,24 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailArmor"];
 
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
 
 // Locates STRing in TEXT occurring only at the beginning of a line
 function indexOfArmorDelimiter(text, str, offset) {
   let currentOffset = offset;
 
   while (currentOffset < text.length) {
     let loc = text.indexOf(str, currentOffset);
 
@@ -29,28 +31,26 @@ function indexOfArmorDelimiter(text, str
 
   return -1;
 }
 
 function searchBlankLine(str, then) {
   var offset = str.search(/\n\s*\r?\n/);
   if (offset === -1) {
     return "";
-  } else {
-    return then(offset);
   }
+  return then(offset);
 }
 
 function indexOfNewline(str, off, then) {
   var offset = str.indexOf("\n", off);
   if (offset === -1) {
     return "";
-  } else {
-    return then(offset);
   }
+  return then(offset);
 }
 
 var EnigmailArmor = {
   /**
    * Locates offsets bracketing PGP armored block in text,
    * starting from given offset, and returns block type string.
    *
    * @param text:          String - ASCII armored text
@@ -58,72 +58,110 @@ var EnigmailArmor = {
    * @param indentStr:     String - prefix that is used for all lines (such as "> ")
    * @param beginIndexObj: Object - o.value will contain offset of first character of block
    * @param endIndexObj:   Object - o.value will contain offset of last character of block (newline)
    * @param indentStrObj:  Object - o.value will contain indent of 1st line
    *
    * @return String - type of block found (e.g. MESSAGE, PUBLIC KEY)
    *           If no block is found, an empty String is returned;
    */
-  locateArmoredBlock: function(text, offset, indentStr, beginIndexObj, endIndexObj, indentStrObj) {
-    EnigmailLog.DEBUG("armor.jsm: Enigmail.locateArmoredBlock: " + offset + ", '" + indentStr + "'\n");
+  locateArmoredBlock(
+    text,
+    offset,
+    indentStr,
+    beginIndexObj,
+    endIndexObj,
+    indentStrObj
+  ) {
+    EnigmailLog.DEBUG(
+      "armor.jsm: Enigmail.locateArmoredBlock: " +
+        offset +
+        ", '" +
+        indentStr +
+        "'\n"
+    );
 
     beginIndexObj.value = -1;
     endIndexObj.value = -1;
 
-    var beginIndex = indexOfArmorDelimiter(text, indentStr + "-----BEGIN PGP ", offset);
+    var beginIndex = indexOfArmorDelimiter(
+      text,
+      indentStr + "-----BEGIN PGP ",
+      offset
+    );
 
     if (beginIndex == -1) {
       var blockStart = text.indexOf("-----BEGIN PGP ");
       if (blockStart >= 0) {
         var indentStart = text.search(/\n.*-----BEGIN PGP /) + 1;
         indentStrObj.value = text.substring(indentStart, blockStart);
         indentStr = indentStrObj.value;
-        beginIndex = indexOfArmorDelimiter(text, indentStr + "-----BEGIN PGP ", offset);
+        beginIndex = indexOfArmorDelimiter(
+          text,
+          indentStr + "-----BEGIN PGP ",
+          offset
+        );
       }
     }
 
-    if (beginIndex == -1)
+    if (beginIndex == -1) {
       return "";
+    }
 
     // Locate newline at end of armor header
     offset = text.indexOf("\n", beginIndex);
 
-    if (offset == -1)
+    if (offset == -1) {
       return "";
+    }
 
-    var endIndex = indexOfArmorDelimiter(text, indentStr + "-----END PGP ", offset);
+    var endIndex = indexOfArmorDelimiter(
+      text,
+      indentStr + "-----END PGP ",
+      offset
+    );
 
-    if (endIndex == -1)
+    if (endIndex == -1) {
       return "";
+    }
 
     // Locate newline at end of PGP block
     endIndex = text.indexOf("\n", endIndex);
 
     if (endIndex == -1) {
       // No terminating newline
       endIndex = text.length - 1;
     }
 
     var blockHeader = text.substr(beginIndex, offset - beginIndex + 1);
 
-    var blockRegex = new RegExp("^" + indentStr +
-      "-----BEGIN PGP (.{1,30})-----\\s*\\r?\\n");
+    var blockRegex = new RegExp(
+      "^" + indentStr + "-----BEGIN PGP (.{1,30})-----\\s*\\r?\\n"
+    );
 
     var matches = blockHeader.match(blockRegex);
 
     var blockType = "";
-    if (matches && (matches.length > 1)) {
+    if (matches && matches.length > 1) {
       blockType = matches[1];
-      EnigmailLog.DEBUG("armor.jsm: Enigmail.locateArmoredBlock: blockType=" + blockType + "\n");
+      EnigmailLog.DEBUG(
+        "armor.jsm: Enigmail.locateArmoredBlock: blockType=" + blockType + "\n"
+      );
     }
 
     if (blockType == "UNVERIFIED MESSAGE") {
       // Skip any unverified message block
-      return EnigmailArmor.locateArmoredBlock(text, endIndex + 1, indentStr, beginIndexObj, endIndexObj, indentStrObj);
+      return EnigmailArmor.locateArmoredBlock(
+        text,
+        endIndex + 1,
+        indentStr,
+        beginIndexObj,
+        endIndexObj,
+        indentStrObj
+      );
     }
 
     beginIndexObj.value = beginIndex;
     endIndexObj.value = endIndex;
 
     return blockType;
   },
 
@@ -135,131 +173,158 @@ var EnigmailArmor = {
    * @return Array of objects with the following structure:
    *        obj.begin:     Number
    *        obj.end:       Number
    *        obj.indent:    String
    *        obj.blocktype: String
    *
    *       if no block was found, an empty array is returned
    */
-  locateArmoredBlocks: function(text) {
+  locateArmoredBlocks(text) {
     var beginObj = {};
     var endObj = {};
     var indentStrObj = {};
     var blocks = [];
     var i = 0;
     var b;
 
-    while ((b = EnigmailArmor.locateArmoredBlock(text, i, "", beginObj, endObj, indentStrObj)) !== "") {
+    while (
+      (b = EnigmailArmor.locateArmoredBlock(
+        text,
+        i,
+        "",
+        beginObj,
+        endObj,
+        indentStrObj
+      )) !== ""
+    ) {
       blocks.push({
         begin: beginObj.value,
         end: endObj.value,
         indent: indentStrObj.value ? indentStrObj.value : "",
-        blocktype: b
+        blocktype: b,
       });
 
       i = endObj.value;
     }
 
-    EnigmailLog.DEBUG("armor.jsm: locateArmorBlocks: Found " + blocks.length + " Blocks\n");
+    EnigmailLog.DEBUG(
+      "armor.jsm: locateArmorBlocks: Found " + blocks.length + " Blocks\n"
+    );
     return blocks;
   },
 
-  extractSignaturePart: function(signatureBlock, part) {
-    EnigmailLog.DEBUG("armor.jsm: Enigmail.extractSignaturePart: part=" + part + "\n");
+  extractSignaturePart(signatureBlock, part) {
+    EnigmailLog.DEBUG(
+      "armor.jsm: Enigmail.extractSignaturePart: part=" + part + "\n"
+    );
 
     return searchBlankLine(signatureBlock, function(offset) {
       return indexOfNewline(signatureBlock, offset + 1, function(offset) {
-        var beginIndex = signatureBlock.indexOf("-----BEGIN PGP SIGNATURE-----", offset + 1);
+        var beginIndex = signatureBlock.indexOf(
+          "-----BEGIN PGP SIGNATURE-----",
+          offset + 1
+        );
         if (beginIndex == -1) {
           return "";
         }
 
         if (part === EnigmailConstants.SIGNATURE_TEXT) {
-          return signatureBlock.substr(offset + 1, beginIndex - offset - 1).
-          replace(/^- -/, "-").
-          replace(/\n- -/g, "\n-").
-          replace(/\r- -/g, "\r-");
+          return signatureBlock
+            .substr(offset + 1, beginIndex - offset - 1)
+            .replace(/^- -/, "-")
+            .replace(/\n- -/g, "\n-")
+            .replace(/\r- -/g, "\r-");
         }
 
         return indexOfNewline(signatureBlock, beginIndex, function(offset) {
-          var endIndex = signatureBlock.indexOf("-----END PGP SIGNATURE-----", offset);
+          var endIndex = signatureBlock.indexOf(
+            "-----END PGP SIGNATURE-----",
+            offset
+          );
           if (endIndex == -1) {
             return "";
           }
 
           var signBlock = signatureBlock.substr(offset, endIndex - offset);
 
           return searchBlankLine(signBlock, function(armorIndex) {
             if (part == EnigmailConstants.SIGNATURE_HEADERS) {
               return signBlock.substr(1, armorIndex);
             }
 
-            return indexOfNewline(signBlock, armorIndex + 1, function(armorIndex) {
+            return indexOfNewline(signBlock, armorIndex + 1, function(
+              armorIndex
+            ) {
               if (part == EnigmailConstants.SIGNATURE_ARMOR) {
-                return signBlock.substr(armorIndex, endIndex - armorIndex).
-                replace(/\s*/g, "");
-              } else {
-                return "";
+                return signBlock
+                  .substr(armorIndex, endIndex - armorIndex)
+                  .replace(/\s*/g, "");
               }
+              return "";
             });
           });
         });
       });
     });
   },
 
   /**
    * Remove all headers from an OpenPGP Armored message and replace them
    * with a set of new headers.
    *
    * @param armorText: String - ASCII armored message
    * @param headers:   Object - key/value pairs of new headers to insert
    *
    * @return String - new armored message
    */
-  replaceArmorHeaders: function(armorText, headers) {
-
+  replaceArmorHeaders(armorText, headers) {
     let text = armorText.replace(/\r\n/g, "\n");
     let i = text.search(/\n/);
 
-    if (i < 0) return armorText;
+    if (i < 0) {
+      return armorText;
+    }
     let m = text.substr(0, i + 1);
 
     for (let j in headers) {
       m += j + ": " + headers[j] + "\n";
     }
 
     i = text.search(/\n\n/);
-    if (i < 0) return armorText;
+    if (i < 0) {
+      return armorText;
+    }
     m += text.substr(i + 1);
 
     return m;
   },
 
   /**
    * Get a list of all headers found in an armor message
    *
    * @param text String - ASCII armored message
    *
    * @return Object: key/value pairs of headers. All keys are in lowercase.
    */
-  getArmorHeaders: function(text) {
+  getArmorHeaders(text) {
     let headers = {};
     let b = this.locateArmoredBlocks(text);
 
     if (b.length === 0) {
       return headers;
     }
 
     let msg = text.substr(b[0].begin);
 
     let lx = new RegExp("\\n" + b[0].indent + "\\r?\\n");
     let hdrEnd = msg.search(lx);
-    if (hdrEnd < 0) return headers;
+    if (hdrEnd < 0) {
+      return headers;
+    }
 
     let lines = msg.substr(0, hdrEnd).split(/\r?\n/);
 
     let rx = new RegExp("^" + b[0].indent + "([^: ]+)(: )(.*)");
     // skip 1st line (ARMOR-line)
     for (let i = 1; i < lines.length; i++) {
       let m = lines[i].match(rx);
       if (m && m.length >= 4) {
@@ -268,26 +333,26 @@ var EnigmailArmor = {
     }
 
     return headers;
   },
 
   /**
    * Split armored blocks into an array of strings
    */
-  splitArmoredBlocks: function(keyBlockStr) {
+  splitArmoredBlocks(keyBlockStr) {
     let myRe = /-----BEGIN PGP (PUBLIC|PRIVATE) KEY BLOCK-----/g;
     let myArray;
     let retArr = [];
     let startIndex = -1;
     while ((myArray = myRe.exec(keyBlockStr)) !== null) {
       if (startIndex >= 0) {
         let s = keyBlockStr.substring(startIndex, myArray.index);
         retArr.push(s);
       }
       startIndex = myArray.index;
     }
 
     retArr.push(keyBlockStr.substring(startIndex));
 
     return retArr;
-  }
-};
\ No newline at end of file
+  },
+};
--- a/mail/extensions/openpgp/content/modules/attachment.jsm
+++ b/mail/extensions/openpgp/content/modules/attachment.jsm
@@ -1,19 +1,20 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailAttachment"];
 
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 var EnigmailAttachment = {
-  getFileName: function(parent, byteData) {
+  getFileName(parent, byteData) {
     const cApi = EnigmailCryptoAPI();
     return cApi.sync(cApi.getFileName(parent, byteData));
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/autoSetup.jsm
+++ b/mail/extensions/openpgp/content/modules/autoSetup.jsm
@@ -8,171 +8,206 @@
 
 /**
  *  Module to determine the type of setup of the user, based on existing emails
  *  found in the inbox
  */
 
 var EXPORTED_SYMBOLS = ["EnigmailAutoSetup"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailAutocrypt = ChromeUtils.import(
+  "chrome://openpgp/content/modules/autocrypt.jsm"
+).EnigmailAutocrypt;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
 const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const EnigmailWks = ChromeUtils.import("chrome://openpgp/content/modules/webKey.jsm").EnigmailWks;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
+const EnigmailWks = ChromeUtils.import(
+  "chrome://openpgp/content/modules/webKey.jsm"
+).EnigmailWks;
+const EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+const EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailGpg = ChromeUtils.import(
+  "chrome://openpgp/content/modules/gpg.jsm"
+).EnigmailGpg;
 
 // Interfaces
-const nsIFolderLookupService = Ci.nsIFolderLookupService;
 const nsIMsgAccountManager = Ci.nsIMsgAccountManager;
-const nsIMsgAccount = Ci.nsIMsgAccount;
-const nsIMsgDBHdr = Ci.nsIMsgDBHdr;
 const nsIMessenger = Ci.nsIMessenger;
 const nsIMsgMessageService = Ci.nsIMsgMessageService;
-const nsIMsgFolder = Ci.nsIMsgFolder;
 
 /**
  * the determined setup type
  */
 var gDeterminedSetupType = {
-  value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED
+  value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED,
 };
 
 var EnigmailAutoSetup = {
-
-  getDeterminedSetupType: async function() {
-    if (gDeterminedSetupType.value === EnigmailConstants.AUTOSETUP_NOT_INITIALIZED) {
-      return await this.determinePreviousInstallType();
+  async getDeterminedSetupType() {
+    if (
+      gDeterminedSetupType.value === EnigmailConstants.AUTOSETUP_NOT_INITIALIZED
+    ) {
+      return this.determinePreviousInstallType();
     }
-    else
-      return gDeterminedSetupType;
+    return gDeterminedSetupType;
   },
 
   /**
    * Identify which type of setup the user had before Enigmail was (re-)installed
    *
    * @return Promise<Object> with:
    *   - value : For each case assigned value, see EnigmailConstants.AUTOSETUP_xxx values
    *   - acSetupMessage {nsIMsgDBHdr}  in case value === 1
    *   - msgHeaders {Object}           in case value === 2
    */
-  determinePreviousInstallType: function() {
-    let self = this;
+  determinePreviousInstallType() {
     gDeterminedSetupType = {
-      value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED
+      value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED,
     };
 
     return new Promise(async (resolve, reject) => {
       EnigmailLog.DEBUG("autoSetup.jsm: determinePreviousInstallType()\n");
 
       try {
-        let msgAccountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(nsIMsgAccountManager);
-        let folderService = Cc["@mozilla.org/mail/folder-lookup;1"].getService(nsIFolderLookupService);
+        let msgAccountManager = Cc[
+          "@mozilla.org/messenger/account-manager;1"
+        ].getService(nsIMsgAccountManager);
         let returnMsgValue = {
-          value: EnigmailConstants.AUTOSETUP_NO_HEADER
+          value: EnigmailConstants.AUTOSETUP_NO_HEADER,
         };
 
         var accounts = msgAccountManager.accounts;
 
         let msgHeaders = [];
-        let autocryptSetupMessage = {};
 
         // If no account, except Local Folders is configured
         if (accounts.length <= 1) {
           gDeterminedSetupType.value = EnigmailConstants.AUTOSETUP_NO_ACCOUNT;
           resolve(gDeterminedSetupType);
           return;
         }
 
         // Iterate through each account
 
         for (var i = 0; i < accounts.length; i++) {
           var account = accounts.queryElementAt(i, Ci.nsIMsgAccount);
           var accountMsgServer = account.incomingServer;
-          EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: scanning account "${accountMsgServer.prettyName}"\n`);
+          EnigmailLog.DEBUG(
+            `autoSetup.jsm: determinePreviousInstallType: scanning account "${
+              accountMsgServer.prettyName
+            }"\n`
+          );
 
           let msgFolderArr = [];
 
           try {
             getMsgFolders(account.incomingServer.rootFolder, msgFolderArr);
-          }
-          catch (e) {
-            EnigmailLog.DEBUG("autoSetup.jsm: determinePreviousInstallType: Error: " + e + "\n");
+          } catch (e) {
+            EnigmailLog.DEBUG(
+              "autoSetup.jsm: determinePreviousInstallType: Error: " + e + "\n"
+            );
           }
 
           if (account.incomingServer.type.search(/^(none|nntp)$/) === 0) {
             // ignore NNTP accounts and "Local Folders" accounts
             continue;
           }
 
           // Iterating through each non empty Folder Database in the Account
 
           for (var k = 0; k < msgFolderArr.length; k++) {
             let msgFolder = msgFolderArr[k];
             let msgDatabase = msgFolderArr[k].msgDatabase;
 
-            if ((msgFolder.flags & Ci.nsMsgFolderFlags.Junk) ||
-              (msgFolder.flags & Ci.nsMsgFolderFlags.Trash) ||
-              (!account.defaultIdentity)) {
+            if (
+              msgFolder.flags & Ci.nsMsgFolderFlags.Junk ||
+              msgFolder.flags & Ci.nsMsgFolderFlags.Trash ||
+              !account.defaultIdentity
+            ) {
               continue;
             }
 
-            EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: scanning folder "${msgFolder.name}"\n`);
+            EnigmailLog.DEBUG(
+              `autoSetup.jsm: determinePreviousInstallType: scanning folder "${
+                msgFolder.name
+              }"\n`
+            );
 
             // Iterating through each message in the Folder
             for (let msgHeader of msgDatabase.ReverseEnumerateMessages()) {
               let msgURI = msgFolder.getUriForMsg(msgHeader);
 
               let msgAuthor = "";
               try {
                 msgAuthor = EnigmailFuncs.stripEmail(msgHeader.author);
-              }
-              catch (x) {}
+              } catch (x) {}
 
               // Listing all the headers in the message
 
-              let messenger = Components.classes["@mozilla.org/messenger;1"].createInstance(nsIMessenger);
-              let mms = messenger.messageServiceFromURI(msgURI).QueryInterface(nsIMsgMessageService);
+              let messenger = Cc["@mozilla.org/messenger;1"].createInstance(
+                nsIMessenger
+              );
+              let mms = messenger
+                .messageServiceFromURI(msgURI)
+                .QueryInterface(nsIMsgMessageService);
 
               let headerObj = await getStreamedHeaders(msgURI, mms);
-              let checkHeaderValues = await checkHeaders(headerObj, msgHeader, msgAuthor, account.defaultIdentity.email, msgFolder, returnMsgValue, msgHeaders);
+              let checkHeaderValues = await checkHeaders(
+                headerObj,
+                msgHeader,
+                msgAuthor,
+                account.defaultIdentity.email,
+                msgFolder,
+                returnMsgValue,
+                msgHeaders
+              );
 
               msgHeaders = checkHeaderValues.msgHeaders;
               returnMsgValue = checkHeaderValues.returnMsgValue;
 
               const currDateInSeconds = getCurrentTime();
               const diffSecond = currDateInSeconds - msgHeader.dateInSeconds;
 
               /**
                   2592000 = No. of Seconds in a Month.
                   This is to ignore 1 month old messages.
               */
               if (diffSecond > 2592000.0) {
                 break;
               }
             }
-
           }
-
         }
         if (returnMsgValue.acSetupMessage) {
-          EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: found AC-Setup message\n`);
+          EnigmailLog.DEBUG(
+            `autoSetup.jsm: determinePreviousInstallType: found AC-Setup message\n`
+          );
           gDeterminedSetupType = returnMsgValue;
           resolve(gDeterminedSetupType);
-        }
-        else {
+        } else {
           EnigmailLog.DEBUG(`msgHeaders.length: ${msgHeaders.length}\n`);
 
           // find newest message to know the protocol
           let latestMsg = null;
           for (let i = 0; i < msgHeaders.length; i++) {
             if (!latestMsg) {
               latestMsg = msgHeaders[i];
             }
@@ -181,63 +216,70 @@ var EnigmailAutoSetup = {
               latestMsg = msgHeaders[i];
             }
           }
 
           if (latestMsg) {
             if (latestMsg.msgType === "Autocrypt") {
               returnMsgValue.value = EnigmailConstants.AUTOSETUP_AC_HEADER;
               returnMsgValue.msgHeaders = msgHeaders;
-            }
-            else {
+            } else {
               returnMsgValue.value = EnigmailConstants.AUTOSETUP_ENCRYPTED_MSG;
               returnMsgValue.msgHeaders = msgHeaders;
             }
           }
 
           let defId = EnigmailFuncs.getDefaultIdentity();
           if (defId) {
             returnMsgValue.userName = defId.fullName;
             returnMsgValue.userEmail = defId.email;
-          }
-          else {
+          } else {
             returnMsgValue.userName = undefined;
             returnMsgValue.userEmail = undefined;
           }
 
           gDeterminedSetupType = returnMsgValue;
-          EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: found type: ${returnMsgValue.value}\n`);
+          EnigmailLog.DEBUG(
+            `autoSetup.jsm: determinePreviousInstallType: found type: ${
+              returnMsgValue.value
+            }\n`
+          );
           resolve(returnMsgValue);
         }
-      }
-      catch (x) {
+      } catch (x) {
         reject(x);
       }
     });
-
   },
 
   /**
    * Process the Autocrypt Setup Message
    *
    * @param {Object} headerValue: contains header and attachment of an Autocrypt Setup Message
    * @param {nsIWindow} passwordWindow: parent window for password dialog
    * @param {nsIWindow} confirmWindow:  parent window for confirmation dialog
    *        (note: split into 2 parent windows for unit tests)
    *
    * @return {Promise<Number>}: Import result.
    *                  1: imported OK
    *                  0: no Autocrypt setup message
    *                 -1: import not OK (wrong password, canceled etc.)
    */
 
-  performAutocryptSetup: async function(headerValue, passwordWindow = null, confirmWindow = null) {
+  async performAutocryptSetup(
+    headerValue,
+    passwordWindow = null,
+    confirmWindow = null
+  ) {
     EnigmailLog.DEBUG("autoSetup.jsm: performAutocryptSetup()\n");
 
-    EnigmailDialog.alert(window, "EnigmailAutocrypt.handleBackupMessage not implemented");
+    EnigmailDialog.alert(
+      confirmWindow,
+      "EnigmailAutocrypt.handleBackupMessage not implemented"
+    );
 
     let imported = 0;
     /*
     if (headerValue.attachment.contentType.search(/^application\/autocrypt-setup$/i) === 0) {
       try {
         let res = await EnigmailAutocrypt.getSetupMessageData(headerValue.attachment.url);
         let passwd = EnigmailWindows.autocryptSetupPasswd(passwordWindow, "input", res.passphraseFormat, res.passphraseHint);
 
@@ -279,42 +321,45 @@ var EnigmailAutoSetup = {
   /**
    * Process accounts with Autocrypt headers
    *
    * @param {Object} setupType: containing Autocrypt headers from accounts
    *
    * @return {Promise<Number>}: Result: 0: OK / 1: failure
    */
 
-  processAutocryptHeader: function(setupType) {
+  processAutocryptHeader(setupType) {
     EnigmailLog.DEBUG("autoSetup.jsm: processAutocryptHeader()\n");
 
     return new Promise(async (resolve, reject) => {
-
       // find newest message to know the protocol
       let latestMsg = null;
       for (let i = 0; i < setupType.msgHeaders.length; i++) {
         if (!latestMsg) {
           latestMsg = setupType.msgHeaders[i];
         }
 
         if (setupType.msgHeaders[i].dateTime > latestMsg) {
           latestMsg = setupType.msgHeaders[i];
         }
       }
 
       let sysType = latestMsg.msgType;
-      EnigmailLog.DEBUG(`autoSetup.jsm: processAutocryptHeader: got type: ${sysType}\n`);
-
+      EnigmailLog.DEBUG(
+        `autoSetup.jsm: processAutocryptHeader: got type: ${sysType}\n`
+      );
 
       for (let i = 0; i < setupType.msgHeaders.length; i++) {
         if (setupType.msgHeaders[i].msgType === "Autocrypt") {
           // FIXME
-          let success = await EnigmailAutocrypt.processAutocryptHeader(setupType.msgHeaders[i].fromAddr, [setupType.msgHeaders[i].msgData],
-            setupType.msgHeaders[i].date);
+          let success = await EnigmailAutocrypt.processAutocryptHeader(
+            setupType.msgHeaders[i].fromAddr,
+            [setupType.msgHeaders[i].msgData],
+            setupType.msgHeaders[i].date
+          );
           if (success !== 0) {
             resolve(1);
           }
         }
       }
       resolve(0);
     });
   },
@@ -322,35 +367,41 @@ var EnigmailAutoSetup = {
   /**
    * Create a new autocrypt key for every configured account and configure the account
    * to use that key. The keys are not protected by a password.
    *
    * The creation is done in the background after waiting timeoutValue ms
    * @param {Number} timeoutValue: number of miliseconds to wait before starting
    *                               the process
    */
-  createKeyForAllAccounts: function(timeoutValue = 1000) {
+  createKeyForAllAccounts(timeoutValue = 1000) {
     EnigmailLog.DEBUG("autoSetup.jsm: createKeyForAllAccounts()\n");
     let self = this;
 
-    EnigmailTimer.setTimeout(async function _f() {
-      let msgAccountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(nsIMsgAccountManager);
+    EnigmailTimer.setTimeout(async function() {
+      let msgAccountManager = Cc[
+        "@mozilla.org/messenger/account-manager;1"
+      ].getService(nsIMsgAccountManager);
       let accounts = msgAccountManager.accounts;
       let createdKeys = [];
 
       for (let i = 0; i < accounts.length; i++) {
         let account = accounts.queryElementAt(i, Ci.nsIMsgAccount);
         let id = account.defaultIdentity;
 
         if (id && id.email) {
           let keyId = await self.createAutocryptKey(id.fullName, id.email);
-          EnigmailLog.DEBUG(`autoSetup.jsm: createKeyForAllAccounts: created key ${keyId}\n`);
+          EnigmailLog.DEBUG(
+            `autoSetup.jsm: createKeyForAllAccounts: created key ${keyId}\n`
+          );
           if (keyId) {
             let keyObj = EnigmailKeyRing.getKeyById(keyId);
-            if (keyObj) createdKeys.push(keyObj);
+            if (keyObj) {
+              createdKeys.push(keyObj);
+            }
             id.setBoolAttribute("enablePgp", true);
             id.setCharAttribute("pgpkeyId", keyId);
             id.setIntAttribute("pgpKeyMode", 1);
             id.setBoolAttribute("pgpMimeMode", true);
             id.setBoolAttribute("pgpSignEncrypted", true);
           }
         }
       }
@@ -364,17 +415,17 @@ var EnigmailAutoSetup = {
    * Create a new autocrypt-complinant key
    * The keys will not be protected by passwords.
    *
    * @param {String} userName:  Display name
    * @param {String} userEmail: Email address
    *
    * @return {Promise<Boolean>}: Success (true = successful)
    */
-  createAutocryptKey: function(userName, userEmail) {
+  createAutocryptKey(userName, userEmail) {
     return new Promise((resolve, reject) => {
       EnigmailLog.DEBUG("autoSetup.jsm: createAutocryptKey()\n");
 
       let keyType = "ECC",
         keyLength = 0;
 
       if (!EnigmailGpg.getGpgFeature("supports-ecc-keys")) {
         // fallback for gpg < 2.1
@@ -384,59 +435,74 @@ var EnigmailAutoSetup = {
 
       let expiry = 1825, // 5 years
         passphrase = "",
         generateObserver = {
           keyId: null,
           backupLocation: null,
           _state: 0,
 
-          onDataAvailable: function(data) {},
-          onStopRequest: function(exitCode) {
-            EnigmailLog.DEBUG("autoSetup.jsm: createAutocryptKey(): key generation complete\n");
+          onDataAvailable(data) {},
+          onStopRequest(exitCode) {
+            EnigmailLog.DEBUG(
+              "autoSetup.jsm: createAutocryptKey(): key generation complete\n"
+            );
             resolve(generateObserver.keyId);
-          }
+          },
         };
 
       try {
-        let keygenRequest = EnigmailKeyRing.generateKey(userName, "", userEmail, expiry, keyLength, keyType, passphrase, generateObserver);
-      }
-      catch (ex) {
-        EnigmailLog.DEBUG("autoSetup.jsm: createAutocryptKey: error: " + ex.message);
+        EnigmailKeyRing.generateKey(
+          userName,
+          "",
+          userEmail,
+          expiry,
+          keyLength,
+          keyType,
+          passphrase,
+          generateObserver
+        );
+      } catch (ex) {
+        EnigmailLog.DEBUG(
+          "autoSetup.jsm: createAutocryptKey: error: " + ex.message
+        );
         resolve(null);
       }
     });
   },
 
   /**
    * Configure Enigmail to use existing keys
    */
-  applyExistingKeys: function() {
-    let msgAccountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(nsIMsgAccountManager);
+  applyExistingKeys() {
+    let msgAccountManager = Cc[
+      "@mozilla.org/messenger/account-manager;1"
+    ].getService(nsIMsgAccountManager);
     let identities = msgAccountManager.allIdentities;
 
     for (let i = 0; i < identities.length; i++) {
       let id = identities.queryElementAt(i, Ci.nsIMsgIdentity);
 
       if (id && id.email) {
         let keyObj = EnigmailKeyRing.getSecretKeyByEmail(id.email);
         if (keyObj) {
-          EnigmailLog.DEBUG(`autoSetup.jsm: applyExistingKeys: found key ${keyObj.keyId}\n`);
+          EnigmailLog.DEBUG(
+            `autoSetup.jsm: applyExistingKeys: found key ${keyObj.keyId}\n`
+          );
           id.setBoolAttribute("enablePgp", true);
           id.setCharAttribute("pgpkeyId", "0x" + keyObj.fpr);
           id.setIntAttribute("pgpKeyMode", 1);
           id.setBoolAttribute("pgpMimeMode", true);
           id.setBoolAttribute("pgpSignEncrypted", true);
         }
       }
     }
-  }
+  },
 };
 
-
 /**
  * Recusrively go through all folders to get a flat array of all sub-folders
  * starting with a parent folder.
  *
  * @param {nsIMsgFolder} folder:       the folder to scan
  * @param {nsIMsgFolder} msgFolderArr: An array to be filled with all folders that contain messages
  */
 
@@ -455,199 +521,218 @@ function getMsgFolders(folder, msgFolder
 
 // Util Function for Extracting manually added Headers
 function streamListener(callback) {
   let streamListener = {
     mAttachments: [],
     mHeaders: [],
     mBusy: true,
 
-    onStartRequest: function(aRequest) {
+    onStartRequest(aRequest) {
       this.mAttachments = [];
       this.mHeaders = [];
       this.mBusy = true;
 
-      var channel = aRequest.QueryInterface(Components.interfaces.nsIChannel);
-      channel.URI.QueryInterface(Components.interfaces.nsIMsgMailNewsUrl);
+      var channel = aRequest.QueryInterface(Ci.nsIChannel);
+      channel.URI.QueryInterface(Ci.nsIMsgMailNewsUrl);
       channel.URI.msgHeaderSink = this; // adds this header sink interface to the channel
     },
-    onStopRequest: function(aRequest, aStatusCode) {
+    onStopRequest(aRequest, aStatusCode) {
       callback();
       this.mBusy = false; // if needed, you can poll this var to see if we are done collecting attachment details
     },
-    onDataAvailable: function(aRequest, aInputStream, aOffset, aCount) {},
-    onStartHeaders: function() {},
-    onEndHeaders: function() {},
-    processHeaders: function(aHeaderNameEnumerator, aHeaderValueEnumerator, aDontCollectAddress) {
+    onDataAvailable(aRequest, aInputStream, aOffset, aCount) {},
+    onStartHeaders() {},
+    onEndHeaders() {},
+    processHeaders(
+      aHeaderNameEnumerator,
+      aHeaderValueEnumerator,
+      aDontCollectAddress
+    ) {
       for (let headerName of aHeaderNameEnumerator) {
         this.mHeaders.push({
           name: headerName.toLowerCase(),
-          value: aHeaderValueEnumerator.getNext()
+          value: aHeaderValueEnumerator.getNext(),
         });
       }
     },
-    handleAttachment: function(aContentType, aUrl, aDisplayName, aUri, aIsExternalAttachment) {
+    handleAttachment(
+      aContentType,
+      aUrl,
+      aDisplayName,
+      aUri,
+      aIsExternalAttachment
+    ) {
       if (aContentType == "text/html") {
         return;
       }
       this.mAttachments.push({
         contentType: aContentType,
         url: aUrl,
         displayName: aDisplayName,
         uri: aUri,
-        isExternal: aIsExternalAttachment
+        isExternal: aIsExternalAttachment,
       });
     },
-    onEndAllAttachments: function() {},
-    onEndMsgDownload: function(aUrl) {},
-    onEndMsgHeaders: function(aUrl) {},
-    onMsgHasRemoteContent: function(aMsgHdr) {},
-    getSecurityInfo: function() {},
-    setSecurityInfo: function(aSecurityInfo) {},
-    getDummyMsgHeader: function() {},
+    onEndAllAttachments() {},
+    onEndMsgDownload(aUrl) {},
+    onEndMsgHeaders(aUrl) {},
+    onMsgHasRemoteContent(aMsgHdr) {},
+    getSecurityInfo() {},
+    setSecurityInfo(aSecurityInfo) {},
+    getDummyMsgHeader() {},
 
-    QueryInterface: function(aIID) {
-      if (aIID.equals(Components.interfaces.nsIStreamListener) ||
-        aIID.equals(Components.interfaces.nsIMsgHeaderSink) ||
-        aIID.equals(Components.interfaces.nsISupports)) {
-        return this;
-      }
-
-      throw Components.results.NS_NOINTERFACE;
-    }
+    QueryInterface: ChromeUtils.generateQI([
+      "nsIStreamListener",
+      "nsIMsgHeaderSink",
+    ]),
   };
 
   return streamListener;
 }
 
 function getStreamedMessage(msgFolder, msgHeader) {
   return new Promise((resolve, reject) => {
     let msgURI = msgFolder.getUriForMsg(msgHeader);
     var listener = streamListener(() => {
       resolve(listener.mAttachments[0]);
     });
-    let messenger = Components.classes["@mozilla.org/messenger;1"].createInstance(nsIMessenger);
-    let mms = messenger.messageServiceFromURI(msgURI).QueryInterface(nsIMsgMessageService);
+    let messenger = Cc["@mozilla.org/messenger;1"].createInstance(nsIMessenger);
+    let mms = messenger
+      .messageServiceFromURI(msgURI)
+      .QueryInterface(nsIMsgMessageService);
     mms.streamMessage(msgURI, listener, null, null, true, "filter");
   });
 }
 
-function checkHeaders(headerObj, msgHeader, msgAuthor, accountEmail, msgFolder, returnMsgValue, msgHeaders) {
+function checkHeaders(
+  headerObj,
+  msgHeader,
+  msgAuthor,
+  accountEmail,
+  msgFolder,
+  returnMsgValue,
+  msgHeaders
+) {
   return new Promise(async (resolve, reject) => {
-    if (headerObj['autocrypt-setup-message'] && msgHeader.author == msgHeader.recipients) {
-
+    if (
+      headerObj["autocrypt-setup-message"] &&
+      msgHeader.author == msgHeader.recipients
+    ) {
       // To extract Attachement for Autocrypt Setup Message
 
-      returnMsgValue.attachment = await getStreamedMessage(msgFolder, msgHeader);
+      returnMsgValue.attachment = await getStreamedMessage(
+        msgFolder,
+        msgHeader
+      );
 
       if (!returnMsgValue.acSetupMessage) {
         returnMsgValue.value = 1;
         returnMsgValue.acSetupMessage = msgHeader;
-      }
-      else if (returnMsgValue.acSetupMessage.date < msgHeader.date) {
+      } else if (returnMsgValue.acSetupMessage.date < msgHeader.date) {
         returnMsgValue.acSetupMessage = msgHeader;
       }
-
-    }
-    else if (msgAuthor == accountEmail &&
-      ("autocrypt" in headerObj)) {
-
+    } else if (msgAuthor == accountEmail && "autocrypt" in headerObj) {
       let msgType = "Autocrypt";
 
       let fromHeaderExist = null;
       for (let j = 0; j < msgHeaders.length; j++) {
         if (msgHeaders[j].fromAddr == msgAuthor) {
           fromHeaderExist = msgHeaders[j];
           break;
         }
       }
 
       if (fromHeaderExist === null) {
         let dateTime = new Date(0);
         try {
           dateTime = jsmime.headerparser.parseDateHeader(headerObj.date);
-        }
-        catch (x) {}
+        } catch (x) {}
 
         let addHeader = {
           fromAddr: msgAuthor,
-          msgType: msgType,
+          msgType,
           msgData: headerObj.autocrypt,
           date: headerObj.date,
-          dateTime: dateTime
+          dateTime,
         };
         msgHeaders.push(addHeader);
-      }
-      else {
+      } else {
         let dateTime = new Date(0);
         try {
           dateTime = jsmime.headerparser.parseDateHeader(headerObj.date);
-        }
-        catch (x) {}
+        } catch (x) {}
         if (dateTime > fromHeaderExist.dateTime) {
           fromHeaderExist.msgData = headerObj.autocrypt;
           fromHeaderExist.date = headerObj.date;
           fromHeaderExist.msgType = msgType;
           fromHeaderExist.dateTime = dateTime;
         }
       }
     }
 
     resolve({
-      'returnMsgValue': returnMsgValue,
-      'msgHeaders': msgHeaders
+      returnMsgValue,
+      msgHeaders,
     });
   });
 }
 
 function getStreamedHeaders(msgURI, mms) {
-
   return new Promise((resolve, reject) => {
-    let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     let headerObj = {};
     try {
-      mms.streamHeaders(msgURI, EnigmailStreams.newStringStreamListener(aRawString => {
-        try {
-          //EnigmailLog.DEBUG(`getStreamedHeaders: ${aRawString}\n`);
-          headers.initialize(aRawString);
+      mms.streamHeaders(
+        msgURI,
+        EnigmailStreams.newStringStreamListener(aRawString => {
+          try {
+            //EnigmailLog.DEBUG(`getStreamedHeaders: ${aRawString}\n`);
+            headers.initialize(aRawString);
 
-          let i = headers.headerNames;
-          for (let hdr of headers.headerNames) {
-            let hdrName = hdr.toLowerCase();
+            let i = headers.headerNames;
+            for (let hdr of headers.headerNames) {
+              let hdrName = hdr.toLowerCase();
 
-            let hdrValue = headers.extractHeader(hdrName, true);
-            headerObj[hdrName] = hdrValue;
-          }
+              let hdrValue = headers.extractHeader(hdrName, true);
+              headerObj[hdrName] = hdrValue;
+            }
 
-          if ("autocrypt" in headerObj) {
-            let acHeader = headers.extractHeader("autocrypt", false);
-            acHeader = acHeader.replace(/keydata=/i, 'keydata="') + '"';
+            if ("autocrypt" in headerObj) {
+              let acHeader = headers.extractHeader("autocrypt", false);
+              acHeader = acHeader.replace(/keydata=/i, 'keydata="') + '"';
 
-            let paramArr = EnigmailMime.getAllParameters(acHeader);
-            paramArr.keydata = paramArr.keydata.replace(/[\r\n\t ]/g, "");
+              let paramArr = EnigmailMime.getAllParameters(acHeader);
+              paramArr.keydata = paramArr.keydata.replace(/[\r\n\t ]/g, "");
 
-            headerObj.autocrypt = "";
-            for (i in paramArr) {
-              if (headerObj.autocrypt.length > 0) {
-                headerObj.autocrypt += "; ";
+              headerObj.autocrypt = "";
+              for (i in paramArr) {
+                if (headerObj.autocrypt.length > 0) {
+                  headerObj.autocrypt += "; ";
+                }
+                headerObj.autocrypt += `${i}="${paramArr[i]}"`;
               }
-              headerObj.autocrypt += `${i}="${paramArr[i]}"`;
             }
+          } catch (e) {
+            reject({});
+            EnigmailLog.DEBUG(
+              "autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n"
+            );
           }
-        }
-        catch (e) {
-          reject({});
-          EnigmailLog.DEBUG("autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n");
-        }
-        resolve(headerObj);
-      }), null, false);
-    }
-    catch (e) {
+          resolve(headerObj);
+        }),
+        null,
+        false
+      );
+    } catch (e) {
       reject({});
-      EnigmailLog.DEBUG("autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n");
+      EnigmailLog.DEBUG(
+        "autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n"
+      );
     }
   });
 }
 
-
 function getCurrentTime() {
   return new Date().getTime() / 1000;
 }
--- a/mail/extensions/openpgp/content/modules/autocrypt.jsm
+++ b/mail/extensions/openpgp/content/modules/autocrypt.jsm
@@ -6,139 +6,180 @@
 
 /**
  *  Module for dealing with received Autocrypt headers, level 0
  *  See details at https://github.com/mailencrypt/autocrypt
  */
 
 var EXPORTED_SYMBOLS = ["EnigmailAutocrypt"];
 
-const Cr = Components.results;
-
-Components.utils.importGlobalProperties(["crypto"]);
+//Cu.importGlobalProperties(["crypto"]);
 
 const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailSqliteDb = ChromeUtils.import("chrome://openpgp/content/modules/sqliteDb.jsm").EnigmailSqliteDb;
-const PromiseUtils = ChromeUtils.import("resource://gre/modules/PromiseUtils.jsm").PromiseUtils;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailOpenPGP = ChromeUtils.import("chrome://openpgp/content/modules/openpgp.jsm").EnigmailOpenPGP;
-const EnigmailRNG = ChromeUtils.import("chrome://openpgp/content/modules/rng.jsm").EnigmailRNG;
-const EnigmailSend = ChromeUtils.import("chrome://openpgp/content/modules/send.jsm").EnigmailSend;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailRules = ChromeUtils.import("chrome://openpgp/content/modules/rules.jsm").EnigmailRules;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailSqliteDb = ChromeUtils.import(
+  "chrome://openpgp/content/modules/sqliteDb.jsm"
+).EnigmailSqliteDb;
+const PromiseUtils = ChromeUtils.import(
+  "resource://gre/modules/PromiseUtils.jsm"
+).PromiseUtils;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailArmor = ChromeUtils.import(
+  "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+const EnigmailRules = ChromeUtils.import(
+  "chrome://openpgp/content/modules/rules.jsm"
+).EnigmailRules;
+const EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 var gCreatedSetupIds = [];
 
 var EnigmailAutocrypt = {
   /**
    * Process the "Autocrypt:" header and if successful store the update in the database
    *
    * @param {String} fromAddr:               Address of sender (From: header)
    * @param {Array of String} headerDataArr: all instances of the Autocrypt: header found in the message
    * @param {String or Number} dateSent:     "Date:" field of the message as readable string or in seconds after 1970-01-01
    * @param {Boolean} autoCryptEnabled:      if true, autocrypt is enabled for the context of the message
    *
    * @return {Promise<Number>}: success: 0 = success, 1+ = failure
    */
-  processAutocryptHeader: async function(fromAddr, headerDataArr, dateSent, autoCryptEnabled = false, isGossip = false) {
-    EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader(): from=" + fromAddr + "\n");
+  async processAutocryptHeader(
+    fromAddr,
+    headerDataArr,
+    dateSent,
+    autoCryptEnabled = false,
+    isGossip = false
+  ) {
+    EnigmailLog.DEBUG(
+      "autocrypt.jsm: processAutocryptHeader(): from=" + fromAddr + "\n"
+    );
     let conn;
 
     try {
       // critical parameters: {param: mandatory}
       const CRITICAL = {
         addr: true,
         keydata: true,
         type: false, // That's actually oboslete according to the Level 1 spec.
-        "prefer-encrypt": false
+        "prefer-encrypt": false,
       };
 
       try {
         fromAddr = EnigmailFuncs.stripEmail(fromAddr).toLowerCase();
-      }
-      catch (ex) {
+      } catch (ex) {
         throw new Error("processAutocryptHeader error " + ex);
       }
       let foundTypes = {};
       let paramArr = [];
 
       for (let hdrNum = 0; hdrNum < headerDataArr.length; hdrNum++) {
-
         let hdr = headerDataArr[hdrNum].replace(/[\r\n \t]/g, "");
         let k = hdr.search(/keydata=/);
         if (k > 0) {
           let d = hdr.substr(k);
           if (d.search(/"/) < 0) {
             hdr = hdr.replace(/keydata=/, 'keydata="') + '"';
           }
         }
 
         paramArr = EnigmailMime.getAllParameters(hdr);
 
         for (let i in CRITICAL) {
           if (CRITICAL[i]) {
             // found mandatory parameter
             if (!(i in paramArr)) {
-              EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: cannot find param '" + i + "'\n");
+              EnigmailLog.DEBUG(
+                "autocrypt.jsm: processAutocryptHeader: cannot find param '" +
+                  i +
+                  "'\n"
+              );
               return 1; // do nothing if not all mandatory parts are present
             }
           }
         }
 
         for (let i in paramArr) {
           if (i.substr(0, 1) !== "_") {
             if (!(i in CRITICAL)) {
-              EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: unknown critical param " + i + "\n");
+              EnigmailLog.DEBUG(
+                "autocrypt.jsm: processAutocryptHeader: unknown critical param " +
+                  i +
+                  "\n"
+              );
               return 2; // do nothing if an unknown critical parameter is found
             }
           }
         }
 
         paramArr.addr = paramArr.addr.toLowerCase();
 
         if (fromAddr !== paramArr.addr) {
-          EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: from Addr " + fromAddr + " != " + paramArr.addr.toLowerCase() + "\n");
+          EnigmailLog.DEBUG(
+            "autocrypt.jsm: processAutocryptHeader: from Addr " +
+              fromAddr +
+              " != " +
+              paramArr.addr.toLowerCase() +
+              "\n"
+          );
 
           return 3;
         }
 
         if (!("type" in paramArr)) {
-          paramArr.type = (isGossip ? "1g" : "1");
-        }
-        else {
+          paramArr.type = isGossip ? "1g" : "1";
+        } else {
           paramArr.type = paramArr.type.toLowerCase();
           if (paramArr.type !== "1") {
-            EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: unknown type " + paramArr.type + "\n");
+            EnigmailLog.DEBUG(
+              "autocrypt.jsm: processAutocryptHeader: unknown type " +
+                paramArr.type +
+                "\n"
+            );
             return 4; // we currently only support 1 (=OpenPGP)
           }
         }
 
         try {
-          let keyData = atob(paramArr.keydata);
-        }
-        catch (ex) {
-          EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: key is not base64-encoded\n");
+          atob(paramArr.keydata); // don't need result
+        } catch (ex) {
+          EnigmailLog.DEBUG(
+            "autocrypt.jsm: processAutocryptHeader: key is not base64-encoded\n"
+          );
           return 5;
         }
 
         if (paramArr.type in foundTypes) {
-          EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: duplicate header for type=" + paramArr.type + "\n");
+          EnigmailLog.DEBUG(
+            "autocrypt.jsm: processAutocryptHeader: duplicate header for type=" +
+              paramArr.type +
+              "\n"
+          );
           return 6; // do not process anything if more than one Autocrypt header for the same type is found
         }
 
         foundTypes[paramArr.type] = 1;
       }
 
       if (isGossip) {
         paramArr["prefer-encrypt"] = "nopreference";
@@ -146,104 +187,125 @@ var EnigmailAutocrypt = {
 
       if (!("prefer-encrypt" in paramArr)) {
         paramArr["prefer-encrypt"] = "nopreference";
       }
 
       let lastDate;
       if (typeof dateSent === "string") {
         lastDate = jsmime.headerparser.parseDateHeader(dateSent);
-      }
-      else {
+      } else {
         lastDate = new Date(dateSent * 1000);
       }
       let now = new Date();
       if (lastDate > now) {
         lastDate = now;
       }
       paramArr.dateSent = lastDate;
 
-      if (("_enigmail_artificial" in paramArr) && (paramArr._enigmail_artificial === "yes")) {
+      if (
+        "_enigmail_artificial" in paramArr &&
+        paramArr._enigmail_artificial === "yes"
+      ) {
         if ("_enigmail_fpr" in paramArr) {
           paramArr.fpr = paramArr._enigmail_fpr;
         }
 
         paramArr.keydata = "";
         paramArr.autocryptDate = 0;
-      }
-      else {
+      } else {
         paramArr.autocryptDate = lastDate;
       }
 
       try {
         conn = await EnigmailSqliteDb.openDatabase();
-      }
-      catch (ex) {
-        EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: could not open database\n");
+      } catch (ex) {
+        EnigmailLog.DEBUG(
+          "autocrypt.jsm: processAutocryptHeader: could not open database\n"
+        );
         return 7;
       }
 
       let resultObj = await findUserRecord(conn, [fromAddr], paramArr.type);
       EnigmailLog.DEBUG("autocrypt.jsm: got " + resultObj.numRows + " rows\n");
       if (resultObj.data.length === 0) {
         await appendUser(conn, paramArr);
-      }
-      else {
+      } else {
         await updateUser(conn, paramArr, resultObj.data, autoCryptEnabled);
       }
 
       EnigmailLog.DEBUG("autocrypt.jsm: OK - closing connection\n");
       conn.close();
       return 0;
-    }
-    catch (err) {
-      EnigmailLog.DEBUG("autocrypt.jsm: error - closing connection: " + err + "\n");
+    } catch (err) {
+      EnigmailLog.DEBUG(
+        "autocrypt.jsm: error - closing connection: " + err + "\n"
+      );
       conn.close();
       return 8;
     }
   },
 
   /**
    * Import autocrypt OpenPGP keys into regular keyring for a given list of email addresses
    * @param {Array of String} emailAddr: email addresses
    * @param {Boolean} acceptGossipKeys: import keys received via gossip
    *
    * @return {Promise<Array of keyObj>}
    */
-  importAutocryptKeys: async function(emailAddr, acceptGossipKeys = false) {
+  async importAutocryptKeys(emailAddr, acceptGossipKeys = false) {
     EnigmailLog.DEBUG("autocrypt.jsm: importAutocryptKeys()\n");
 
     let keyArr = await this.getOpenPGPKeyForEmail(emailAddr);
-    if (!keyArr) return [];
+    if (!keyArr) {
+      return [];
+    }
 
     let importedKeys = [];
     let now = new Date();
     let prev = null;
 
     for (let i = 0; i < keyArr.length; i++) {
-      if (prev && prev.email === keyArr[i].email && prev.type === "1" && keyArr[i].type === "1g") {
+      if (
+        prev &&
+        prev.email === keyArr[i].email &&
+        prev.type === "1" &&
+        keyArr[i].type === "1g"
+      ) {
         // skip if we have "gossip" key preceeded by a "regular" key
         continue;
       }
       if (!acceptGossipKeys && keyArr[i].type === "1g") {
-        EnigmailLog.DEBUG(`autocrypt.jsm: importAutocryptKeys: skipping gossip key for ${keyArr[i].email}\n`);
+        EnigmailLog.DEBUG(
+          `autocrypt.jsm: importAutocryptKeys: skipping gossip key for ${
+            keyArr[i].email
+          }\n`
+        );
         continue;
       }
 
       prev = keyArr[i];
       if ((now - keyArr[i].lastAutocrypt) / (1000 * 60 * 60 * 24) < 366) {
         // only import keys received less than 12 months ago
         try {
           let keyData = atob(keyArr[i].keyData);
           if (keyData.length > 1) {
-            importedKeys = await this.applyKeyFromKeydata(keyData, keyArr[i].email, keyArr[i].state, keyArr[i].type);
+            importedKeys = await this.applyKeyFromKeydata(
+              keyData,
+              keyArr[i].email,
+              keyArr[i].state,
+              keyArr[i].type
+            );
           }
-        }
-        catch (ex) {
-          EnigmailLog.DEBUG("autocrypt.jsm importAutocryptKeys: exception " + ex.toString() + "\n");
+        } catch (ex) {
+          EnigmailLog.DEBUG(
+            "autocrypt.jsm importAutocryptKeys: exception " +
+              ex.toString() +
+              "\n"
+          );
         }
       }
     }
 
     return importedKeys;
   },
 
   /**
@@ -251,170 +313,198 @@ var EnigmailAutocrypt = {
    *
    * @param {String} keyData - String key data (BLOB, binary form)
    * @param {String} email - email address associated with key
    * @param {String} autocryptState - mutual or nopreference
    * @param {String} type - autocrypt header type (1 / 1g)
    *
    * @return {Promise<Array of keys>} list of imported keys
    */
-  applyKeyFromKeydata: async function(keyData, email, autocryptState, type) {
+  async applyKeyFromKeydata(keyData, email, autocryptState, type) {
+    throw new Error("Not implemented");
+
+    /*
     let keysObj = {};
     let importedKeys = [];
 
-    let pubkey = EnigmailOpenPGP.enigmailFuncs.bytesToArmor(EnigmailOpenPGP.armor.public_key, keyData);
+    // TODO: need a MPL version of bytesToArmor
+    let pubkey = EnigmailOpenPGP.enigmailFuncs.bytesToArmor(
+      EnigmailOpenPGP.armor.public_key,
+      keyData
+    );
     await EnigmailKeyRing.importKeyAsync(null, false, pubkey, "", {}, keysObj);
 
     if (keysObj.value) {
       importedKeys = importedKeys.concat(keysObj.value);
 
       if (keysObj.value.length > 0) {
         let key = EnigmailKeyRing.getKeyById(keysObj.value[0]);
 
         // enable encryption if state (prefer-encrypt) is "mutual";
         // otherwise, disable it explicitely
-        let signEncrypt = (autocryptState === "mutual" ? 1 : 0);
+        let signEncrypt = autocryptState === "mutual" ? 1 : 0;
 
         if (key && key.fpr) {
           let ruleObj = {
             email: `{${EnigmailConstants.AC_RULE_PREFIX}${email}}`,
             keyList: `0x${key.fpr}`,
             sign: signEncrypt,
             encrypt: signEncrypt,
             pgpMime: 2,
-            flags: 0
+            flags: 0,
           };
 
           EnigmailRules.insertOrUpdateRule(ruleObj);
           await this.setKeyImported(null, email);
         }
       }
     }
 
     return importedKeys;
+    */
   },
 
   /**
    * Update key in the Autocrypt database to mark it "imported in keyring"
    */
-  setKeyImported: async function(connection, email) {
+  async setKeyImported(connection, email) {
     EnigmailLog.DEBUG(`autocrypt.jsm: setKeyImported(${email})\n`);
     try {
       let conn = connection;
       if (!conn) {
         conn = await EnigmailSqliteDb.openDatabase();
       }
-      let updateStr = "update autocrypt_keydata set keyring_inserted = '1' where email = :email;";
+      let updateStr =
+        "update autocrypt_keydata set keyring_inserted = '1' where email = :email;";
 
       let updateObj = {
-        email: email.toLowerCase()
+        email: email.toLowerCase(),
       };
 
       await new Promise((resolve, reject) =>
-        conn.executeTransaction(function _trx() {
-          conn.execute(updateStr, updateObj).then(r => {
-            resolve(r);
-          }).catch(err => {
-            EnigmailLog.DEBUG(`autocrypt.jsm: setKeyImported: error ${err}\n`);
-            reject(err);
-          });
-        }));
+        conn.executeTransaction(function() {
+          conn
+            .execute(updateStr, updateObj)
+            .then(r => {
+              resolve(r);
+            })
+            .catch(err => {
+              EnigmailLog.DEBUG(
+                `autocrypt.jsm: setKeyImported: error ${err}\n`
+              );
+              reject(err);
+            });
+        })
+      );
 
-      if (!connection) conn.close();
-    }
-    catch (err) {
+      if (!connection) {
+        conn.close();
+      }
+    } catch (err) {
       EnigmailLog.DEBUG(`autocrypt.jsm: setKeyImported: error ${err}\n`);
       throw err;
     }
   },
 
   /**
    * Go through all emails in the autocrypt store and determine which keys already
    * have a per-recipient rule
    */
-  updateAllImportedKeys: async function() {
+  async updateAllImportedKeys() {
     EnigmailLog.DEBUG(`autocrypt.jsm: updateAllImportedKeys()\n`);
     try {
       let conn = await EnigmailSqliteDb.openDatabase();
 
       let rows = [];
-      await conn.execute("select email, type from autocrypt_keydata where type = '1';", {},
-        function _onRow(record) {
+      await conn.execute(
+        "select email, type from autocrypt_keydata where type = '1';",
+        {},
+        function(record) {
           rows.push(record.getResultByName("email"));
-        });
+        }
+      );
 
       for (let i in rows) {
-        let r = EnigmailRules.getRuleByEmail(`${EnigmailConstants.AC_RULE_PREFIX}${rows[i]}`);
+        let r = EnigmailRules.getRuleByEmail(
+          `${EnigmailConstants.AC_RULE_PREFIX}${rows[i]}`
+        );
         if (r) {
           await this.setKeyImported(conn, rows[i], "1");
         }
-
       }
       EnigmailLog.DEBUG(`autocrypt.jsm: updateAllImportedKeys done\n`);
 
       conn.close();
-    }
-    catch (err) {
+    } catch (err) {
       EnigmailLog.DEBUG(`autocrypt.jsm: updateAllImportedKeys: error ${err}\n`);
       throw err;
     }
   },
 
   /**
    * Find an autocrypt OpenPGP key for a given list of email addresses
    * @param emailAddr: Array of String - email addresses
    *
    * @return Promise(<Array of Object>)
    *      Object: {fpr, keyData, lastAutocrypt}
    */
-  getOpenPGPKeyForEmail: function(emailAddr) {
-    EnigmailLog.DEBUG("autocrypt.jsm: getOpenPGPKeyForEmail(" + emailAddr.join(",") + ")\n");
+  getOpenPGPKeyForEmail(emailAddr) {
+    EnigmailLog.DEBUG(
+      "autocrypt.jsm: getOpenPGPKeyForEmail(" + emailAddr.join(",") + ")\n"
+    );
 
     let conn;
 
     return new Promise((resolve, reject) => {
-      EnigmailSqliteDb.openDatabase().then(
-        function onConnection(connection) {
-          conn = connection;
-          return findUserRecord(conn, emailAddr, "1,1g");
-        },
-        function onError(error) {
-          EnigmailLog.DEBUG("autocrypt.jsm: getOpenPGPKeyForEmail: could not open database\n");
-          reject("getOpenPGPKeyForEmail1 error " + error);
-        }
-      ).then(
-        function gotData(resultObj) {
-          EnigmailLog.DEBUG("autocrypt.jsm: getOpenPGPKeyForEmail got " + resultObj.numRows + " rows\n");
+      EnigmailSqliteDb.openDatabase()
+        .then(
+          function(connection) {
+            conn = connection;
+            return findUserRecord(conn, emailAddr, "1,1g");
+          },
+          function(error) {
+            EnigmailLog.DEBUG(
+              "autocrypt.jsm: getOpenPGPKeyForEmail: could not open database\n"
+            );
+            reject("getOpenPGPKeyForEmail1 error " + error);
+          }
+        )
+        .then(function(resultObj) {
+          EnigmailLog.DEBUG(
+            "autocrypt.jsm: getOpenPGPKeyForEmail got " +
+              resultObj.numRows +
+              " rows\n"
+          );
           conn.close();
 
           if (resultObj.data.length === 0) {
             resolve(null);
-          }
-          else {
+          } else {
             let retArr = [];
             for (let i in resultObj.data) {
               let record = resultObj.data[i];
               retArr.push({
                 email: record.getResultByName("email"),
                 fpr: record.getResultByName("fpr"),
                 keyData: record.getResultByName("keydata"),
                 state: record.getResultByName("state"),
                 type: record.getResultByName("type"),
-                lastAutocrypt: new Date(record.getResultByName("last_seen_autocrypt"))
+                lastAutocrypt: new Date(
+                  record.getResultByName("last_seen_autocrypt")
+                ),
               });
             }
 
             resolve(retArr);
           }
-        }
-      ).
-      catch((err) => {
-        conn.close();
-        reject("getOpenPGPKeyForEmail: error " + err);
-      });
+        })
+        .catch(err => {
+          conn.close();
+          reject("getOpenPGPKeyForEmail: error " + err);
+        });
     });
   },
 
   /**
    * Create Autocrypt Setup Message
    *
    * @param identity: Object - nsIMsgIdentity
    *
@@ -535,56 +625,63 @@ var EnigmailAutocrypt = {
         else {
           reject(99);
         }
       });
     });
   },
   */
 
-
   /**
    * get the data of the attachment of a setup message
    *
    * @param attachmentUrl: String - URL of the attachment
    *
    * @return Promise(Object):
    *            attachmentData:   String - complete attachment data
    *            passphraseFormat: String - extracted format from the header (e.g. numeric9x4) [optional]
    *            passphraseHint:   String - 1st two digits of the password [optional]
    */
-  getSetupMessageData: function(attachmentUrl) {
+  getSetupMessageData(attachmentUrl) {
     EnigmailLog.DEBUG("autocrypt.jsm: getSetupMessageData()\n");
 
     return new Promise((resolve, reject) => {
       let s = EnigmailStreams.newStringStreamListener(data => {
         let start = {},
           end = {};
-        let msgType = EnigmailArmor.locateArmoredBlock(data, 0, "", start, end, {});
+        let msgType = EnigmailArmor.locateArmoredBlock(
+          data,
+          0,
+          "",
+          start,
+          end,
+          {}
+        );
 
         if (msgType === "MESSAGE") {
-          EnigmailLog.DEBUG("autocrypt.jsm: getSetupMessageData: got backup key\n");
+          EnigmailLog.DEBUG(
+            "autocrypt.jsm: getSetupMessageData: got backup key\n"
+          );
           let armorHdr = EnigmailArmor.getArmorHeaders(data);
 
           let passphraseFormat = "generic";
           if ("passphrase-format" in armorHdr) {
             passphraseFormat = armorHdr["passphrase-format"];
           }
           let passphraseHint = "";
           if ("passphrase-begin" in armorHdr) {
             passphraseHint = armorHdr["passphrase-begin"];
           }
 
           resolve({
             attachmentData: data,
-            passphraseFormat: passphraseFormat,
-            passphraseHint: passphraseHint
+            passphraseFormat,
+            passphraseHint,
           });
-        }
-        else {
+        } else {
           reject("getSetupMessageData");
         }
       });
 
       let channel = EnigmailStreams.createChannel(attachmentUrl);
       channel.asyncOpen(s, null);
     });
   },
@@ -645,82 +742,98 @@ var EnigmailAutocrypt = {
       });
     });
   },
   */
 
   /**
    * Determine if a message id was self-created (only during same TB session)
    */
-  isSelfCreatedSetupMessage: function(messageId) {
-    return (gCreatedSetupIds.indexOf(messageId) >= 0);
+  isSelfCreatedSetupMessage(messageId) {
+    return gCreatedSetupIds.includes(messageId);
   },
 
   /**
    * Check if an account is set up with OpenPGP and if the configured key is valid
    *
    * @param emailAddr: String - email address identifying the account
    *
    * @return Boolean: true: account is valid / false: OpenPGP not configured or key not valid
    */
-  isAccountSetupForPgp: function(emailAddr) {
-    let id = EnigmailStdlib.getIdentityForEmail(EnigmailFuncs.stripEmail(emailAddr).toLowerCase());
+  isAccountSetupForPgp(emailAddr) {
+    let id = EnigmailStdlib.getIdentityForEmail(
+      EnigmailFuncs.stripEmail(emailAddr).toLowerCase()
+    );
     let keyObj = null;
 
-    if (!(id && id.identity)) return false;
-    if (!id.identity.getBoolAttribute("enablePgp")) return false;
+    if (!(id && id.identity)) {
+      return false;
+    }
+    if (!id.identity.getBoolAttribute("enablePgp")) {
+      return false;
+    }
 
     if (id.identity.getIntAttribute("pgpKeyMode") === 1) {
-      keyObj = EnigmailKeyRing.getKeyById(id.identity.getCharAttribute("pgpkeyId"));
-    }
-    else {
+      keyObj = EnigmailKeyRing.getKeyById(
+        id.identity.getCharAttribute("pgpkeyId")
+      );
+    } else {
       keyObj = EnigmailKeyRing.getSecretKeyByUserId(emailAddr);
     }
 
-    if (!keyObj) return false;
-    if (!keyObj.secretAvailable) return false;
+    if (!keyObj) {
+      return false;
+    }
+    if (!keyObj.secretAvailable) {
+      return false;
+    }
 
     let o = keyObj.getEncryptionValidity();
-    if (!o.keyValid) return false;
+    if (!o.keyValid) {
+      return false;
+    }
     o = keyObj.getSigningValidity();
-    if (!o.keyValid) return false;
+    if (!o.keyValid) {
+      return false;
+    }
 
     return true;
   },
 
   /**
    * Delete the record for a user from the autocrypt keystore
    * The record with the highest precedence is deleted (i.e. type=1 before type=1g)
    */
-  deleteUser: async function(email, type) {
+  async deleteUser(email, type) {
     EnigmailLog.DEBUG(`autocrypt.jsm: deleteUser(${email})\n`);
     let conn = await EnigmailSqliteDb.openDatabase();
 
-    let updateStr = "delete from autocrypt_keydata where email = :email and type = :type";
+    let updateStr =
+      "delete from autocrypt_keydata where email = :email and type = :type";
     let updateObj = {
-      email: email,
-      type: type
+      email,
+      type,
     };
 
     await new Promise((resolve, reject) => {
-      conn.executeTransaction(function _trx() {
-        conn.execute(updateStr, updateObj).then(
-          function _ok() {
+      conn.executeTransaction(function() {
+        conn
+          .execute(updateStr, updateObj)
+          .then(function() {
             resolve();
-          }
-        ).catch(function _err() {
-          reject("update failed");
-        });
+          })
+          .catch(function() {
+            reject("update failed");
+          });
       });
     });
     EnigmailLog.DEBUG(" deletion complete\n");
 
     conn.close();
-  }
-
+  },
 };
 
 /**
  * Find the database record for a given email address and type
  *
  * @param connection: Object - SQLite connection
  * @param emails      Array of String - Email addresses to search
  * @param type:       String - types to search (in lowercase), separated by comma
@@ -732,17 +845,17 @@ var EnigmailAutocrypt = {
 async function findUserRecord(connection, emails, type) {
   EnigmailLog.DEBUG("autocrypt.jsm: findUserRecord\n");
 
   let data = [];
   let t = type.split(/[ ,]+/);
 
   let queryParam = {
     e0: emails[0],
-    t0: t[0]
+    t0: t[0],
   };
 
   let numRows = 0;
 
   let search = ":e0";
   for (let i = 1; i < emails.length; i++) {
     search += ", :e" + i;
     queryParam["e" + i] = emails[i].toLowerCase();
@@ -751,31 +864,36 @@ async function findUserRecord(connection
   let typeParam = ":t0";
   for (let i = 1; i < t.length; i++) {
     typeParam += ", :t" + i;
     queryParam["t" + i] = t[i];
   }
 
   try {
     await connection.execute(
-      "select * from autocrypt_keydata where email in (" + search + ") and type in (" + typeParam + ") order by email, type", queryParam,
-      function _onRow(row) {
+      "select * from autocrypt_keydata where email in (" +
+        search +
+        ") and type in (" +
+        typeParam +
+        ") order by email, type",
+      queryParam,
+      function(row) {
         EnigmailLog.DEBUG("autocrypt.jsm: findUserRecord - got row\n");
         data.push(row);
         ++numRows;
-      });
-  }
-  catch (x) {
+      }
+    );
+  } catch (x) {
     EnigmailLog.DEBUG(`autocrypt.jsm: findUserRecord: error ${x}\n`);
     throw x;
   }
 
   return {
-    data: data,
-    numRows: numRows
+    data,
+    numRows,
   };
 }
 
 /**
  * Create new database record for an Autorypt header
  *
  * @param connection: Object - SQLite connection
  * @param paramsArr:  Object - the Autocrypt header parameters
@@ -785,41 +903,44 @@ async function findUserRecord(connection
 async function appendUser(connection, paramsArr) {
   EnigmailLog.DEBUG("autocrypt.jsm: appendUser(" + paramsArr.addr + ")\n");
 
   if (!("fpr" in paramsArr)) {
     await getFprForKey(paramsArr);
   }
 
   return new Promise((resolve, reject) => {
-
     if (paramsArr.autocryptDate == 0) {
       // do not insert record for non-autocrypt mail
       resolve();
       return;
     }
 
-    connection.executeTransaction(function _trx() {
-      connection.execute("insert into autocrypt_keydata (email, keydata, fpr, type, last_seen_autocrypt, last_seen, state) values " +
-        "(:email, :keyData, :fpr, :type, :lastAutocrypt, :lastSeen, :state)", {
-          email: paramsArr.addr.toLowerCase(),
-          keyData: paramsArr.keydata,
-          fpr: ("fpr" in paramsArr ? paramsArr.fpr : ""),
-          type: paramsArr.type,
-          lastAutocrypt: paramsArr.dateSent.toJSON(),
-          lastSeen: paramsArr.dateSent.toJSON(),
-          state: paramsArr["prefer-encrypt"]
-        }).then(
-        function _ok() {
+    connection.executeTransaction(function() {
+      connection
+        .execute(
+          "insert into autocrypt_keydata (email, keydata, fpr, type, last_seen_autocrypt, last_seen, state) values " +
+            "(:email, :keyData, :fpr, :type, :lastAutocrypt, :lastSeen, :state)",
+          {
+            email: paramsArr.addr.toLowerCase(),
+            keyData: paramsArr.keydata,
+            fpr: "fpr" in paramsArr ? paramsArr.fpr : "",
+            type: paramsArr.type,
+            lastAutocrypt: paramsArr.dateSent.toJSON(),
+            lastSeen: paramsArr.dateSent.toJSON(),
+            state: paramsArr["prefer-encrypt"],
+          }
+        )
+        .then(function() {
           EnigmailLog.DEBUG("autocrypt.jsm: appendUser - OK\n");
           resolve();
-        }
-      ).catch(function _err() {
-        reject("appendUser");
-      });
+        })
+        .catch(function() {
+          reject("appendUser");
+        });
     });
   });
 }
 
 /**
  * Update the record for an email address and type, if the email we got is newer
  * than the latest record we already stored
  *
@@ -829,121 +950,142 @@ async function appendUser(connection, pa
  * @param autoCryptEnabled: Boolean: is autocrypt enabled for this transaction
  *
  * @return Promise
  */
 async function updateUser(connection, paramsArr, resultRows, autoCryptEnabled) {
   EnigmailLog.DEBUG("autocrypt.jsm: updateUser\n");
 
   let currData = resultRows[0];
-  let deferred = PromiseUtils.defer();
+  PromiseUtils.defer();
 
   let lastSeen = new Date(currData.getResultByName("last_seen"));
   let lastAutocrypt = new Date(currData.getResultByName("last_seen_autocrypt"));
-  let notGossip = (currData.getResultByName("state") !== "gossip");
+  let notGossip = currData.getResultByName("state") !== "gossip";
   let currentKeyData = currData.getResultByName("keydata");
-  let isKeyInKeyring = (currData.getResultByName("keyring_inserted") === "1");
+  let isKeyInKeyring = currData.getResultByName("keyring_inserted") === "1";
 
-  if (lastSeen >= paramsArr.dateSent ||
-    (paramsArr["prefer-encrypt"] === "gossip" && notGossip)) {
-    EnigmailLog.DEBUG("autocrypt.jsm: updateUser: not a relevant new latest message\n");
+  if (
+    lastSeen >= paramsArr.dateSent ||
+    (paramsArr["prefer-encrypt"] === "gossip" && notGossip)
+  ) {
+    EnigmailLog.DEBUG(
+      "autocrypt.jsm: updateUser: not a relevant new latest message\n"
+    );
 
     return;
   }
 
   EnigmailLog.DEBUG("autocrypt.jsm: updateUser: updating latest message\n");
 
   let updateStr;
   let updateObj;
 
   if (paramsArr.autocryptDate > 0) {
     lastAutocrypt = paramsArr.autocryptDate;
     if (!("fpr" in paramsArr)) {
       await getFprForKey(paramsArr);
     }
 
-    updateStr = "update autocrypt_keydata set state = :state, keydata = :keyData, last_seen_autocrypt = :lastAutocrypt, " +
+    updateStr =
+      "update autocrypt_keydata set state = :state, keydata = :keyData, last_seen_autocrypt = :lastAutocrypt, " +
       "fpr = :fpr, last_seen = :lastSeen where email = :email and type = :type";
     updateObj = {
       email: paramsArr.addr.toLowerCase(),
       state: paramsArr["prefer-encrypt"],
       keyData: paramsArr.keydata,
-      fpr: ("fpr" in paramsArr ? paramsArr.fpr : ""),
+      fpr: "fpr" in paramsArr ? paramsArr.fpr : "",
       type: paramsArr.type,
       lastAutocrypt: lastAutocrypt.toJSON(),
-      lastSeen: paramsArr.dateSent.toJSON()
+      lastSeen: paramsArr.dateSent.toJSON(),
     };
-  }
-  else {
-    updateStr = "update autocrypt_keydata set state = :state, last_seen = :lastSeen where email = :email and type = :type";
+  } else {
+    updateStr =
+      "update autocrypt_keydata set state = :state, last_seen = :lastSeen where email = :email and type = :type";
     updateObj = {
       email: paramsArr.addr.toLowerCase(),
       state: paramsArr["prefer-encrypt"],
       type: paramsArr.type,
-      lastSeen: paramsArr.dateSent.toJSON()
+      lastSeen: paramsArr.dateSent.toJSON(),
     };
   }
 
   if (!("fpr" in paramsArr)) {
     await getFprForKey(paramsArr);
   }
 
   await new Promise((resolve, reject) => {
-    connection.executeTransaction(function _trx() {
-      connection.execute(updateStr, updateObj).then(
-        function _ok() {
+    connection.executeTransaction(function() {
+      connection
+        .execute(updateStr, updateObj)
+        .then(function() {
           resolve();
-        }
-      ).catch(function _err() {
-        reject("update failed");
-      });
+        })
+        .catch(function() {
+          reject("update failed");
+        });
     });
   });
 
-  if (autoCryptEnabled && isKeyInKeyring && (currentKeyData !== paramsArr.keydata)) {
-    await updateKeyIfNeeded(paramsArr.addr.toLowerCase(), paramsArr.keydata, paramsArr.fpr, paramsArr.type, paramsArr["prefer-encrypt"]);
+  if (
+    autoCryptEnabled &&
+    isKeyInKeyring &&
+    currentKeyData !== paramsArr.keydata
+  ) {
+    await updateKeyIfNeeded(
+      paramsArr.addr.toLowerCase(),
+      paramsArr.keydata,
+      paramsArr.fpr,
+      paramsArr.type,
+      paramsArr["prefer-encrypt"]
+    );
   }
-
-  return;
 }
 
-
 /**
  * Determine if a key in the keyring should be replaced by a new (or updated) key
  * @param {String} email - Email address
  * @param {String} keydata - new keydata to import
  * @param {String} fpr - fingerprint of new key
  * @param {String} keyType - key type (1 / 1g)
  * @param {String} autocryptState - mutual or nopreference
  *
  * @return {Promise<Boolean>} - key updated
  */
 async function updateKeyIfNeeded(email, keydata, fpr, keyType, autocryptState) {
-  let ruleNode = EnigmailRules.getRuleByEmail(EnigmailConstants.AC_RULE_PREFIX + email);
-  if (!ruleNode) return false;
+  let ruleNode = EnigmailRules.getRuleByEmail(
+    EnigmailConstants.AC_RULE_PREFIX + email
+  );
+  if (!ruleNode) {
+    return false;
+  }
 
   let doImport = false;
 
   let currentKeyId = ruleNode.getAttribute("keyList");
   if (`0x${fpr}` === currentKeyId || keyType === "1") {
     doImport = true;
-  }
-  else {
+  } else {
     // Gossip keys
     let keyObj = EnigmailKeyRing.getKeyById(currentKeyId);
     let encOk = keyObj.getEncryptionValidity().keyValid;
 
     if (!encOk) {
       // current key is not valid anymore
       doImport = true;
     }
   }
 
   if (doImport) {
-    await EnigmailAutocrypt.applyKeyFromKeydata(atob(keydata), email, autocryptState, keyType);
+    await EnigmailAutocrypt.applyKeyFromKeydata(
+      atob(keydata),
+      email,
+      autocryptState,
+      keyType
+    );
   }
 
   return doImport;
 }
 
 /**
  * Set the fpr attribute for a given key parameter object
  */
@@ -960,117 +1102,144 @@ async function getFprForKey(paramsArr) {
 
     for (let k in keyInfo) {
       keyArr.push(keyInfo[k]);
     }
 
     if (keyArr.length === 1) {
       paramsArr.fpr = keyArr[0].fpr;
     }
-  }
-  catch (x) {}
+  } catch (x) {}
 }
 
-
 /**
  * Create the 9x4 digits backup code as defined in the Autocrypt spec
  *
  * @return String: xxxx-xxxx-...
  */
-
+/*
 function createBackupCode() {
   let bkpCode = "";
 
   for (let i = 0; i < 9; i++) {
-    if (i > 0) bkpCode += "-";
+    if (i > 0) {
+      bkpCode += "-";
+    }
 
     let a = new Uint8Array(4);
     crypto.getRandomValues(a);
     for (let j = 0; j < 4; j++) {
       bkpCode += String(a[j] % 10);
     }
   }
   return bkpCode;
 }
 
-
 function createBackupOuterMsg(toEmail, encryptedMsg) {
-
   let boundary = EnigmailMime.createBoundary();
 
-  let msgStr = 'To: ' + toEmail + '\r\n' +
-    'From: ' + toEmail + '\r\n' +
-    'Autocrypt-Setup-Message: v1\r\n' +
-    'Subject: ' + EnigmailLocale.getString("autocrypt.setupMsg.subject") + '\r\n' +
-    'Content-type: multipart/mixed; boundary="' + boundary + '"\r\n\r\n' +
-    '--' + boundary + '\r\n' +
-    'Content-Type: text/plain\r\n\r\n' +
-    EnigmailLocale.getString("autocryptSetupReq.setupMsg.desc") + '\r\n\r\n' +
-    EnigmailLocale.getString("autocrypt.setupMsg.msgBody") + '\r\n\r\n' +
-    EnigmailLocale.getString("autocryptSetupReq.setupMsg.backup") + '\r\n' +
-    '--' + boundary + '\r\n' +
-    'Content-Type: application/autocrypt-setup\r\n' +
+  let msgStr =
+    "To: " +
+    toEmail +
+    "\r\n" +
+    "From: " +
+    toEmail +
+    "\r\n" +
+    "Autocrypt-Setup-Message: v1\r\n" +
+    "Subject: " +
+    EnigmailLocale.getString("autocrypt.setupMsg.subject") +
+    "\r\n" +
+    'Content-type: multipart/mixed; boundary="' +
+    boundary +
+    '"\r\n\r\n' +
+    "--" +
+    boundary +
+    "\r\n" +
+    "Content-Type: text/plain\r\n\r\n" +
+    EnigmailLocale.getString("autocryptSetupReq.setupMsg.desc") +
+    "\r\n\r\n" +
+    EnigmailLocale.getString("autocrypt.setupMsg.msgBody") +
+    "\r\n\r\n" +
+    EnigmailLocale.getString("autocryptSetupReq.setupMsg.backup") +
+    "\r\n" +
+    "--" +
+    boundary +
+    "\r\n" +
+    "Content-Type: application/autocrypt-setup\r\n" +
     'Content-Disposition: attachment; filename="autocrypt-setup-message.html"\r\n\r\n' +
-    '<html><body>\r\n' +
-    '<p>' + EnigmailLocale.getString("autocrypt.setupMsg.fileTxt") + '</p>\r\n' +
-    '<pre>\r\n' +
+    "<html><body>\r\n" +
+    "<p>" +
+    EnigmailLocale.getString("autocrypt.setupMsg.fileTxt") +
+    "</p>\r\n" +
+    "<pre>\r\n" +
     encryptedMsg +
-    '</pre></body></html>\r\n' +
-    '--' + boundary + '--\r\n';
+    "</pre></body></html>\r\n" +
+    "--" +
+    boundary +
+    "--\r\n";
 
   return msgStr;
 }
-
+*/
 
 /**
  * @return Object:
  *          fpr:           String - FPR of the imported key
  *          preferEncrypt: String - Autocrypt preferEncrypt value (e.g. mutual)
  */
+/*
 function importSetupKey(keyData) {
-
   EnigmailLog.DEBUG("autocrypt.jsm: importSetupKey()\n");
 
   let preferEncrypt = "nopreference"; // Autocrypt default according spec
   let start = {},
     end = {},
     keyObj = {};
 
-  let msgType = EnigmailArmor.locateArmoredBlock(keyData, 0, "", start, end, {});
+  let msgType = EnigmailArmor.locateArmoredBlock(
+    keyData,
+    0,
+    "",
+    start,
+    end,
+    {}
+  );
   if (msgType === "PRIVATE KEY BLOCK") {
-
     let headers = EnigmailArmor.getArmorHeaders(keyData);
     if ("autocrypt-prefer-encrypt" in headers) {
       preferEncrypt = headers["autocrypt-prefer-encrypt"];
     }
 
     let r = EnigmailKeyRing.importKey(null, false, keyData, "", {}, keyObj);
 
     if (r === 0 && keyObj.value && keyObj.value.length > 0) {
       return {
         fpr: keyObj.value[0],
-        preferEncrypt: preferEncrypt
+        preferEncrypt,
       };
     }
   }
 
   return null;
 }
 
-
 function updateRuleForEmail(email, preferEncrypt, fpr = null) {
-  let node = EnigmailRules.getRuleByEmail(EnigmailConstants.AC_RULE_PREFIX + email);
+  let node = EnigmailRules.getRuleByEmail(
+    EnigmailConstants.AC_RULE_PREFIX + email
+  );
 
   if (node) {
-    let signEncrypt = (preferEncrypt === "mutual" ? "1" : "0");
+    let signEncrypt = preferEncrypt === "mutual" ? "1" : "0";
 
-    if (node.getAttribute("sign") !== signEncrypt ||
-      node.getAttribute("encrypt") !== signEncrypt) {
-
+    if (
+      node.getAttribute("sign") !== signEncrypt ||
+      node.getAttribute("encrypt") !== signEncrypt
+    ) {
       node.setAttribute("sign", signEncrypt);
       node.setAttribute("encrypt", signEncrypt);
       if (fpr) {
         node.setAttribute("keyList", `0x${fpr}`);
       }
       EnigmailRules.saveRulesFile();
     }
   }
 }
+*/
--- a/mail/extensions/openpgp/content/modules/clipboard.jsm
+++ b/mail/extensions/openpgp/content/modules/clipboard.jsm
@@ -5,102 +5,104 @@
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailClipboard"];
 
 // Import the Services module for future use, if we're not in
 // a browser window where it's already loaded.
-const Services = ChromeUtils.import('resource://gre/modules/Services.jsm').Services;
-
-
-// Create a constructor for the built-in supports-string class.
-const nsSupportsString = Components.Constructor("@mozilla.org/supports-string;1", "nsISupportsString");
-
-function SupportsString(str) {
-  // Create an instance of the supports-string class
-  var res = nsSupportsString();
-
-  // Store the JavaScript string that we want to wrap in the new nsISupportsString object
-  res.data = str;
-  return res;
-}
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 // Create a constructor for the built-in transferable class
-const nsTransferable = Components.Constructor("@mozilla.org/widget/transferable;1", "nsITransferable");
+const nsTransferable = Components.Constructor(
+  "@mozilla.org/widget/transferable;1",
+  "nsITransferable"
+);
 
 // Create a wrapper to construct an nsITransferable instance and set its source to the given window, when necessary
 function Transferable(source) {
   let res = nsTransferable();
-  if ('init' in res) {
+  if ("init" in res) {
     // When passed a Window object, find a suitable privacy context for it.
-    if (source instanceof Ci.nsIDOMWindow)
-      source = source.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation);
+    if (source instanceof Ci.nsIDOMWindow) {
+      source = source
+        .QueryInterface(Ci.nsIInterfaceRequestor)
+        .getInterface(Ci.nsIWebNavigation);
+    }
 
     res.init(source);
   }
   return res;
 }
 
 var EnigmailClipboard = {
-
   /**
    * Get the content string of a clipboard
    *
    * @param window       : nsIWindow or nsIDOMWindow of caller
    * @param clipBoardType: Number - clipboard type according to nsIClipboard
    *
    * @return String - content of clipBoard
    */
 
-  getClipboardContent: function(window, clipBoardType) {
+  getClipboardContent(window, clipBoardType) {
     if (!window) {
       throw new Error("window is a required parameter");
     }
 
-    let clipBoard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
+    let clipBoard = Services.clipboard;
     let data = {};
     let cBoardContent = "";
 
-    if (clipBoardType !== clipBoard.kSelectionClipboard || clipBoard.supportsSelectionClipboard()) {
+    if (
+      clipBoardType !== clipBoard.kSelectionClipboard ||
+      clipBoard.supportsSelectionClipboard()
+    ) {
       try {
         let transferable = Transferable(window);
         transferable.addDataFlavor("text/unicode");
         clipBoard.getData(transferable, clipBoardType);
         let flavour = {};
         transferable.getAnyTransferData(flavour, data);
         cBoardContent = data.value.QueryInterface(Ci.nsISupportsString).data;
-      }
-      catch (ex) {}
+      } catch (ex) {}
     }
     return cBoardContent;
   },
 
   /**
    * Set the global (and if available, the selection clipboard)
    *
    * @param str: String - data to set
    * @param clipBoardType: Number - clipboard type according to nsIClipboard.
    *             If not provided, the global plus the selection clipboard will be used
    *
    * @return Boolean: true - success / false - failure
    */
-  setClipboardContent: function(str, clipBoardType) {
+  setClipboardContent(str, clipBoardType) {
     let useClipboard = clipBoardType;
     if (clipBoardType === undefined) {
       useClipboard = Ci.nsIClipboard.kGlobalClipboard;
     }
     try {
-      let clipBoard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
-      let clipBoardHlp = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
+      let clipBoard = Services.clipboard;
+      let clipBoardHlp = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(
+        Ci.nsIClipboardHelper
+      );
       clipBoardHlp.copyStringToClipboard(str, useClipboard);
-      if (clipBoard.supportsSelectionClipboard() &&
-        (useClipboard === Ci.nsIClipboard.kSelectionClipboard || clipBoardType === undefined)) {
-        clipBoardHlp.copyStringToClipboard(str, Ci.nsIClipboard.kSelectionClipboard);
+      if (
+        clipBoard.supportsSelectionClipboard() &&
+        (useClipboard === Ci.nsIClipboard.kSelectionClipboard ||
+          clipBoardType === undefined)
+      ) {
+        clipBoardHlp.copyStringToClipboard(
+          str,
+          Ci.nsIClipboard.kSelectionClipboard
+        );
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       return false;
     }
     return true;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/commandLine.jsm
+++ b/mail/extensions/openpgp/content/modules/commandLine.jsm
@@ -1,47 +1,60 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailCommandLine"];
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
 
-const NS_ENIGCLINE_SERVICE_CID = Components.ID("{847b3ab1-7ab1-11d4-8f02-006008948af5}");
+const NS_ENIGCLINE_SERVICE_CID = Components.ID(
+  "{847b3ab1-7ab1-11d4-8f02-006008948af5}"
+);
 const NS_CLINE_SERVICE_CONTRACTID = "@mozilla.org/enigmail/cline-handler;1";
 
 function Handler() {}
 
 Handler.prototype = {
   classDescription: "Enigmail Key Management CommandLine Service",
   classID: NS_ENIGCLINE_SERVICE_CID,
   contractID: NS_CLINE_SERVICE_CONTRACTID,
-  QueryInterface: EnigmailCompat.generateQI(["nsICommandLineHandler", "nsIFactory"]),
+  QueryInterface: EnigmailCompat.generateQI([
+    "nsICommandLineHandler",
+    "nsIFactory",
+  ]),
 
   // nsICommandLineHandler
-  handle: function(cmdLine) {
+  handle(cmdLine) {
     if (cmdLine.handleFlag("pgpkeyman", false)) {
       cmdLine.preventDefault = true; // do not open main app window
 
-      const wwatch = Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher);
-      wwatch.openWindow(null, "chrome://openpgp/content/ui/enigmailKeyManager.xhtml", "_blank", "chrome,dialog=no,all", cmdLine);
+      Services.ww.openWindow(
+        null,
+        "chrome://openpgp/content/ui/enigmailKeyManager.xhtml",
+        "_blank",
+        "chrome,dialog=no,all",
+        cmdLine
+      );
     }
   },
 
   helpInfo: "  -pgpkeyman         Open the OpenPGP key management.\n",
 
-  lockFactory: function(lock) {}
+  lockFactory(lock) {},
 };
 
 var EnigmailCommandLine = {
-  Handler: Handler,
+  Handler,
   categoryRegistry: {
     category: "command-line-handler",
     entry: "m-cline-enigmail",
-    serviceName: NS_CLINE_SERVICE_CONTRACTID
-  }
+    serviceName: NS_CLINE_SERVICE_CONTRACTID,
+  },
 };
--- a/mail/extensions/openpgp/content/modules/compat.jsm
+++ b/mail/extensions/openpgp/content/modules/compat.jsm
@@ -5,99 +5,113 @@
 "use strict";
 
 /**
  *  compatibility Module
  */
 
 var EXPORTED_SYMBOLS = ["EnigmailCompat"];
 
-const XPCOM_APPINFO = "@mozilla.org/xre/app-info;1";
-
 var MailUtils;
 
 MailUtils = ChromeUtils.import("resource:///modules/MailUtils.jsm").MailUtils;
 
-var gCompFields, gPgpMimeObj;
-
 var EnigmailCompat = {
-  generateQI: function(aCid) {
+  generateQI(aCid) {
     return ChromeUtils.generateQI(aCid);
   },
 
-  getExistingFolder: function(folderUri) {
+  getExistingFolder(folderUri) {
     return MailUtils.getExistingFolder(folderUri);
   },
 
   /**
    * Get a mail URL from a uriSpec
    *
    * @param uriSpec: String - URI of the desired message
    *
    * @return Object: nsIURL or nsIMsgMailNewsUrl object
    */
-  getUrlFromUriSpec: function(uriSpec) {
+  getUrlFromUriSpec(uriSpec) {
     try {
-      if (!uriSpec)
+      if (!uriSpec) {
         return null;
+      }
 
-      let messenger = Cc["@mozilla.org/messenger;1"].getService(Ci.nsIMessenger);
+      let messenger = Cc["@mozilla.org/messenger;1"].getService(
+        Ci.nsIMessenger
+      );
       let msgService = messenger.messageServiceFromURI(uriSpec);
 
       let url;
       // TB
       let urlObj = {};
       msgService.GetUrlForUri(uriSpec, urlObj, null);
 
       url = urlObj.value;
 
       if (url.scheme == "file") {
         return url;
       }
-      else {
-        return url.QueryInterface(Ci.nsIMsgMailNewsUrl);
-      }
 
-    }
-    catch (ex) {
+      return url.QueryInterface(Ci.nsIMsgMailNewsUrl);
+    } catch (ex) {
       return null;
     }
   },
   /**
    * Copy a file to a mail folder.
    *   in nsIFile aFile,
    *   in nsIMsgFolder dstFolder,
    *   in unsigned long aMsgFlags,
    *   in ACString aMsgKeywords,
    *   in nsIMsgCopyServiceListener listener,
    *   in nsIMsgWindow msgWindow
    */
-  copyFileToMailFolder: function(file, destFolder, msgFlags, msgKeywords, listener, msgWindow) {
-    let copySvc = Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(Ci.nsIMsgCopyService);
+  copyFileToMailFolder(
+    file,
+    destFolder,
+    msgFlags,
+    msgKeywords,
+    listener,
+    msgWindow
+  ) {
+    let copySvc = Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(
+      Ci.nsIMsgCopyService
+    );
 
-    return copySvc.CopyFileMessage(file, destFolder, null, false, msgFlags, msgKeywords, listener, msgWindow);
+    return copySvc.CopyFileMessage(
+      file,
+      destFolder,
+      null,
+      false,
+      msgFlags,
+      msgKeywords,
+      listener,
+      msgWindow
+    );
   },
 
   /**
    * Get functions that wrap the changes on nsITreeView between TB 60 and TB 68
    *
    * @param treeObj
    * @param listViewHolder
    *
    * @return {Object}
    */
-  getTreeCompatibleFuncs: function(treeObj, listViewHolder) {
+  getTreeCompatibleFuncs(treeObj, listViewHolder) {
     return {
-      getCellAt: function(x,y) {
+      getCellAt(x, y) {
         return treeObj.getCellAt(x, y);
       },
-      rowCountChanged: function(a, b) {
+      rowCountChanged(a, b) {
         return treeObj.rowCountChanged(a, b);
       },
-      invalidate: function() {
+      invalidate() {
         return treeObj.invalidate();
       },
-      invalidateRow: function(r) {
+      invalidateRow(r) {
         return treeObj.invalidateRow(r);
-      }
+      },
     };
   },
 };
--- a/mail/extensions/openpgp/content/modules/configBackup.jsm
+++ b/mail/extensions/openpgp/content/modules/configBackup.jsm
@@ -1,99 +1,106 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailConfigBackup"];
 
-
-
-
-
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailRules = ChromeUtils.import("chrome://openpgp/content/modules/rules.jsm").EnigmailRules;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailRules = ChromeUtils.import(
+  "chrome://openpgp/content/modules/rules.jsm"
+).EnigmailRules;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
 
 const TYPE_BOOL = 1;
 const TYPE_CHAR = 2;
 const TYPE_INT = 3;
 
 const IdentityPref = {
   enablePgp: TYPE_BOOL,
   pgpkeyId: TYPE_CHAR,
   pgpKeyMode: TYPE_INT,
   pgpSignPlain: TYPE_BOOL,
   pgpSignEncrypted: TYPE_BOOL,
   defaultSigningPolicy: TYPE_INT,
   defaultEncryptionPolicy: TYPE_INT,
   openPgpUrlName: TYPE_CHAR,
   pgpMimeMode: TYPE_BOOL,
   attachPgpKey: TYPE_BOOL,
-  autoEncryptDrafts: TYPE_BOOL
+  autoEncryptDrafts: TYPE_BOOL,
 };
 
 var EnigmailConfigBackup = {
-
-  getAccountManager: function() {
-    let amService = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+  getAccountManager() {
+    let amService = Cc["@mozilla.org/messenger/account-manager;1"].getService(
+      Ci.nsIMsgAccountManager
+    );
     return amService;
   },
 
   /**
    * itereate over all identities and execute a callback function for each found element
    *
    * @param callbackFunc  function  - the callback for each identity
    *                  The function takes the identity as 1st argument, i.e.
    *                    callbackFunc(nsIMsgIdentity)
    * @return  - undefined
    */
-  forAllIdentitites: function(callbackFunc) {
-
+  forAllIdentitites(callbackFunc) {
     let amService = this.getAccountManager();
 
     amService.LoadAccounts(); // ensure accounts are really loaded
     let a = amService.allIdentities;
     for (let i = 0; i < a.length; i++) {
       let id = a.queryElementAt(i, Ci.nsIMsgIdentity);
       try {
         callbackFunc(id);
-      }
-      catch (ex) {
-        EnigmailLog.DEBUG("configBackup.jsm: forAllIdentitites: exception " + ex.toString() + "\n");
+      } catch (ex) {
+        EnigmailLog.DEBUG(
+          "configBackup.jsm: forAllIdentitites: exception " +
+            ex.toString() +
+            "\n"
+        );
       }
     }
   },
 
   /**
    * backup Enigmail preferences to a file
    *
    * @param outputFile  nsIFile - handle to file to be saved
    *
    * @return 0: success, other values: failure
    */
-  backupPrefs: function(outputFile) {
+  backupPrefs(outputFile) {
     EnigmailLog.DEBUG("configBackup.jsm: backupPrefs\n");
 
     // user preference
     let prefObj = {
       enigmailPrefs: EnigmailPrefs.getAllPrefs(),
-      mailIdentities: {}
+      mailIdentities: {},
     };
 
     function getIdentityPrefs(identity) {
-
-      if (!identity.getBoolAttribute("enablePgp")) return; // do nothing if Enigmail disabled
+      if (!identity.getBoolAttribute("enablePgp")) {
+        return;
+      } // do nothing if Enigmail disabled
 
       let keyObj = {
         emailAddress: identity.email.toLowerCase(),
-        identityName: identity.identityName
+        identityName: identity.identityName,
       };
 
       for (let pref in IdentityPref) {
         switch (IdentityPref[pref]) {
           case TYPE_BOOL:
             keyObj[pref] = identity.getBoolAttribute(pref);
             break;
           case TYPE_INT:
@@ -131,28 +138,35 @@ var EnigmailConfigBackup = {
    *
    * @param inputFile  nsIFile - handle to file to be saved
    *
    * @return Object: {
    *     retVal:       Number - 0: success, other values: failure
    *     unmatchedIds: Array (String): keys of identities
    *   }
    */
-  restorePrefs: function(inputFile) {
+  restorePrefs(inputFile) {
     EnigmailLog.DEBUG("configBackup.jsm: restorePrefs\n");
     var prefObj;
     var returnObj = {
       retVal: -1,
-      unmatchedIds: []
+      unmatchedIds: [],
     };
 
     function setIdentityPref(identity) {
       for (let k in prefObj.mailIdentities) {
-        if (prefObj.mailIdentities[k].emailAddress === identity.email.toLowerCase()) {
-          EnigmailLog.DEBUG("configBackup.jsm: setIdentityPref: restoring values for " + identity.email + "\n");
+        if (
+          prefObj.mailIdentities[k].emailAddress ===
+          identity.email.toLowerCase()
+        ) {
+          EnigmailLog.DEBUG(
+            "configBackup.jsm: setIdentityPref: restoring values for " +
+              identity.email +
+              "\n"
+          );
           prefObj.mailIdentities[k].foundMatchingEmail = true;
           let keyObj = prefObj.mailIdentities[k];
           for (let pref in IdentityPref) {
             switch (IdentityPref[pref]) {
               case TYPE_BOOL:
                 identity.setBoolAttribute(pref, keyObj[pref]);
                 break;
               case TYPE_INT:
@@ -162,27 +176,28 @@ var EnigmailConfigBackup = {
                 identity.setCharAttribute(pref, keyObj[pref]);
                 break;
             }
           }
           return;
         }
       }
 
-      EnigmailLog.DEBUG("configBackup.jsm: setIdentityPref: no matching data for " + identity.email + "\n");
+      EnigmailLog.DEBUG(
+        "configBackup.jsm: setIdentityPref: no matching data for " +
+          identity.email +
+          "\n"
+      );
     }
 
     // Profile must be a single UTF-8 encoded JSON object.
     try {
       let jsonStr = EnigmailFiles.readFile(inputFile);
       prefObj = JSON.parse(jsonStr);
 
-      var nsIPB = Ci.nsIPrefBranch;
-      var branch = EnigmailPrefs.getPrefBranch();
-
       // Set all options recorded in the JSON file.
       for (let name in prefObj.enigmailPrefs) {
         EnigmailPrefs.setPref(name, prefObj.enigmailPrefs[name]);
       }
 
       this.forAllIdentitites(setIdentityPref);
 
       for (let i in prefObj.mailIdentities) {
@@ -194,20 +209,19 @@ var EnigmailConfigBackup = {
       let am = this.getAccountManager();
       am.saveAccountInfo();
       EnigmailPrefs.savePrefs();
 
       if ("rules" in prefObj) {
         EnigmailRules.loadRulesFromString(prefObj.rules);
         EnigmailRules.saveRulesFile();
       }
-
-    }
-    catch (ex) {
-      EnigmailLog.ERROR("configBackup.jsm: restorePrefs - exception " + ex.toString() + "\n");
+    } catch (ex) {
+      EnigmailLog.ERROR(
+        "configBackup.jsm: restorePrefs - exception " + ex.toString() + "\n"
+      );
       return returnObj;
     }
 
     returnObj.retVal = 0;
     return returnObj;
-  }
-
+  },
 };
--- a/mail/extensions/openpgp/content/modules/configure.jsm
+++ b/mail/extensions/openpgp/content/modules/configure.jsm
@@ -3,45 +3,75 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailConfigure"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailAutoSetup = ChromeUtils.import("chrome://openpgp/content/modules/autoSetup.jsm").EnigmailAutoSetup;
-const EnigmailSqliteDb = ChromeUtils.import("chrome://openpgp/content/modules/sqliteDb.jsm").EnigmailSqliteDb;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-// Interfaces
-const nsIFolderLookupService = Ci.nsIFolderLookupService;
-const nsIMsgAccountManager = Ci.nsIMsgAccountManager;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+const EnigmailApp = ChromeUtils.import(
+  "chrome://openpgp/content/modules/app.jsm"
+).EnigmailApp;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const EnigmailAutoSetup = ChromeUtils.import(
+  "chrome://openpgp/content/modules/autoSetup.jsm"
+).EnigmailAutoSetup;
 
 /**
  * Upgrade sending prefs
  * (v1.6.x -> v1.7 )
  */
 function upgradePrefsSending() {
   EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending()\n");
 
   var cbs = EnigmailPrefs.getPref("confirmBeforeSend");
   var ats = EnigmailPrefs.getPref("alwaysTrustSend");
   var ksfr = EnigmailPrefs.getPref("keepSettingsForReply");
-  EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending cbs=" + cbs + " ats=" + ats + " ksfr=" + ksfr + "\n");
+  EnigmailLog.DEBUG(
+    "enigmailCommon.jsm: upgradePrefsSending cbs=" +
+      cbs +
+      " ats=" +
+      ats +
+      " ksfr=" +
+      ksfr +
+      "\n"
+  );
 
   // Upgrade confirmBeforeSend (bool) to confirmBeforeSending (int)
   switch (cbs) {
     case false:
       EnigmailPrefs.setPref("confirmBeforeSending", 0); // never
       break;
     case true:
       EnigmailPrefs.setPref("confirmBeforeSending", 1); // always
@@ -56,246 +86,260 @@ function upgradePrefsSending() {
     case true:
       EnigmailPrefs.setPref("acceptedKeys", 1); // all
       break;
   }
 
   // if all settings are default settings, use convenient encryption
   if (cbs === false && ats === true && ksfr === true) {
     EnigmailPrefs.setPref("encryptionModel", 0); // convenient
-    EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending() encryptionModel=0 (convenient)\n");
-  }
-  else {
+    EnigmailLog.DEBUG(
+      "enigmailCommon.jsm: upgradePrefsSending() encryptionModel=0 (convenient)\n"
+    );
+  } else {
     EnigmailPrefs.setPref("encryptionModel", 1); // manually
-    EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending() encryptionModel=1 (manually)\n");
+    EnigmailLog.DEBUG(
+      "enigmailCommon.jsm: upgradePrefsSending() encryptionModel=1 (manually)\n"
+    );
   }
 
   // clear old prefs
   EnigmailPrefs.getPrefBranch().clearUserPref("confirmBeforeSend");
   EnigmailPrefs.getPrefBranch().clearUserPref("alwaysTrustSend");
 }
 
 /**
  * Replace short key IDs with FPR in identity settings
  * (v1.9 -> v2.0)
  */
 function replaceKeyIdWithFpr() {
   try {
-    const GetKeyRing = EnigmailLazy.loader("enigmail/keyRing.jsm", "EnigmailKeyRing");
+    const GetKeyRing = EnigmailLazy.loader(
+      "enigmail/keyRing.jsm",
+      "EnigmailKeyRing"
+    );
 
-    var accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+    var accountManager = Cc[
+      "@mozilla.org/messenger/account-manager;1"
+    ].getService(Ci.nsIMsgAccountManager);
     for (var i = 0; i < accountManager.allIdentities.length; i++) {
-      var id = accountManager.allIdentities.queryElementAt(i, Ci.nsIMsgIdentity);
+      var id = accountManager.allIdentities.queryElementAt(
+        i,
+        Ci.nsIMsgIdentity
+      );
       if (id.getBoolAttribute("enablePgp")) {
         let keyId = id.getCharAttribute("pgpkeyId");
 
         if (keyId.search(/^(0x)?[a-fA-F0-9]{8}$/) === 0) {
-
           EnigmailCore.getService();
 
           let k = GetKeyRing().getKeyById(keyId);
           if (k) {
             id.setCharAttribute("pgpkeyId", "0x" + k.fpr);
-          }
-          else {
+          } else {
             id.setCharAttribute("pgpkeyId", "");
           }
         }
       }
     }
-  }
-  catch (ex) {
+  } catch (ex) {
     EnigmailDialog.alert("config upgrade: error" + ex.toString());
   }
 }
 
-
 /**
  * Change the default to PGP/MIME for all accounts, except nntp
  * (v1.8.x -> v1.9)
  */
 function defaultPgpMime() {
-  let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+  let accountManager = Cc[
+    "@mozilla.org/messenger/account-manager;1"
+  ].getService(Ci.nsIMsgAccountManager);
   let changedSomething = false;
 
   for (let acct = 0; acct < accountManager.accounts.length; acct++) {
     let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);
     if (ac.incomingServer.type.search(/(pop3|imap|movemail)/) >= 0) {
-
       for (let i = 0; i < ac.identities.length; i++) {
         let id = ac.identities.queryElementAt(i, Ci.nsIMsgIdentity);
-        if (id.getBoolAttribute("enablePgp") && !id.getBoolAttribute("pgpMimeMode")) {
+        if (
+          id.getBoolAttribute("enablePgp") &&
+          !id.getBoolAttribute("pgpMimeMode")
+        ) {
           changedSomething = true;
         }
         id.setBoolAttribute("pgpMimeMode", true);
       }
     }
   }
 
   if (EnigmailPrefs.getPref("advancedUser") && changedSomething) {
-    EnigmailDialog.alert(null,
-      EnigmailLocale.getString("preferences.defaultToPgpMime"));
+    EnigmailDialog.alert(
+      null,
+      EnigmailLocale.getString("preferences.defaultToPgpMime")
+    );
   }
 }
 
 /**
  * set the Autocrypt prefer-encrypt option to "mutual" for all existing
  * accounts
  */
 function setAutocryptForOldAccounts() {
   try {
-    let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
-    let changedSomething = false;
+    let accountManager = Cc[
+      "@mozilla.org/messenger/account-manager;1"
+    ].getService(Ci.nsIMsgAccountManager);
 
     for (let acct = 0; acct < accountManager.accounts.length; acct++) {
       let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);
       if (ac.incomingServer.type.search(/(pop3|imap|movemail)/) >= 0) {
         ac.incomingServer.setIntValue("acPreferEncrypt", 1);
       }
     }
-  }
-  catch (ex) {}
+  } catch (ex) {}
 }
 
 function setDefaultKeyServer() {
   EnigmailLog.DEBUG("configure.jsm: setDefaultKeyServer()\n");
 
   let ks = EnigmailPrefs.getPref("keyserver");
 
   if (ks.search(/^ldaps?:\/\//) < 0) {
     ks = "vks://keys.openpgp.org, " + ks;
   }
 
   ks = ks.replace(/hkps:\/\/keys.openpgp.org/g, "vks://keys.openpgp.org");
   EnigmailPrefs.setPref("keyserver", ks);
 }
 
-
-
 function displayUpgradeInfo() {
   EnigmailLog.DEBUG("configure.jsm: displayUpgradeInfo()\n");
   try {
     EnigmailWindows.openMailTab("chrome://openpgp/content/ui/upgradeInfo.html");
-  }
-  catch (ex) {}
+  } catch (ex) {}
 }
 
-
 var EnigmailConfigure = {
   /**
    * configureEnigmail: main function for configuring Enigmail during the first run
    * this method is called from core.jsm if Enigmail has not been set up before
    * (determined via checking the configuredVersion in the preferences)
    *
    * @param {nsIWindow} win:                 The parent window. Null if no parent window available
    * @param {Boolean}   startingPreferences: if true, called while switching to new preferences
    *                        (to avoid re-check for preferences)
    *
    * @return {Promise<null>}
    */
-  configureEnigmail: async function(win, startingPreferences) {
+  async configureEnigmail(win, startingPreferences) {
     EnigmailLog.DEBUG("configure.jsm: configureEnigmail()\n");
 
     if (!EnigmailStdlib.hasConfiguredAccounts()) {
-      EnigmailLog.DEBUG("configure.jsm: configureEnigmail: no account configured. Waiting 60 seconds.\n");
+      EnigmailLog.DEBUG(
+        "configure.jsm: configureEnigmail: no account configured. Waiting 60 seconds.\n"
+      );
 
       // try again in 60 seconds
-      EnigmailTimer.setTimeout(
-        function _f() {
-          EnigmailConfigure.configureEnigmail(win, startingPreferences);
-        },
-        60000);
+      EnigmailTimer.setTimeout(function() {
+        EnigmailConfigure.configureEnigmail(win, startingPreferences);
+      }, 60000);
       return;
     }
 
     let oldVer = EnigmailPrefs.getPref("configuredVersion");
 
-    let vc = Cc["@mozilla.org/xpcom/version-comparator;1"].getService(Ci.nsIVersionComparator);
-
     if (oldVer === "") {
       try {
-        let setupResult = await EnigmailAutoSetup.determinePreviousInstallType();
+        await EnigmailAutoSetup.determinePreviousInstallType();
 
         switch (EnigmailAutoSetup.value) {
           case EnigmailConstants.AUTOSETUP_NOT_INITIALIZED:
           case EnigmailConstants.AUTOSETUP_NO_ACCOUNT:
             break;
           default:
-            EnigmailPrefs.setPref("configuredVersion", EnigmailApp.getVersion());
+            EnigmailPrefs.setPref(
+              "configuredVersion",
+              EnigmailApp.getVersion()
+            );
             EnigmailWindows.openSetupWizard(win);
         }
-      }
-      catch(x) {
+      } catch (x) {
         // ignore exceptions and proceed without setup wizard
       }
-    }
-    else {
-      if (vc.compare(oldVer, "1.7a1pre") < 0) {
+    } else {
+      if (Services.vc.compare(oldVer, "1.7a1pre") < 0) {
         // 1: rules only
         //     => assignKeysByRules true; rest false
         // 2: rules & email addresses (normal)
         //     => assignKeysByRules/assignKeysByEmailAddr/assignKeysManuallyIfMissing true
         // 3: email address only (no rules)
         //     => assignKeysByEmailAddr/assignKeysManuallyIfMissing true
         // 4: manually (always prompt, no rules)
         //     => assignKeysManuallyAlways true
         // 5: no rules, no key selection
         //     => assignKeysByRules/assignKeysByEmailAddr true
 
         upgradePrefsSending();
       }
-      if (vc.compare(oldVer, "1.7") < 0) {
+      if (Services.vc.compare(oldVer, "1.7") < 0) {
         // open a modal dialog. Since this might happen during the opening of another
         // window, we have to do this asynchronously
-        EnigmailTimer.setTimeout(
-          function _cb() {
-            var doIt = EnigmailDialog.confirmDlg(win,
-              EnigmailLocale.getString("enigmailCommon.versionSignificantlyChanged"),
-              EnigmailLocale.getString("enigmailCommon.checkPreferences"),
-              EnigmailLocale.getString("dlg.button.close"));
-            if (!startingPreferences && doIt) {
-              // same as:
-              // - EnigmailWindows.openPrefWindow(window, true, 'sendingTab');
-              // but
-              // - without starting the service again because we do that right now
-              // - and modal (waiting for its end)
-              win.openDialog("chrome://openpgp/content/ui/pref-enigmail.xhtml",
-                "_blank", "chrome,resizable=yes,modal", {
-                  'showBasic': true,
-                  'clientType': 'thunderbird',
-                  'selectTab': 'sendingTab'
-                });
-            }
-          }, 100);
+        EnigmailTimer.setTimeout(function() {
+          var doIt = EnigmailDialog.confirmDlg(
+            win,
+            EnigmailLocale.getString(
+              "enigmailCommon.versionSignificantlyChanged"
+            ),
+            EnigmailLocale.getString("enigmailCommon.checkPreferences"),
+            EnigmailLocale.getString("dlg.button.close")
+          );
+          if (!startingPreferences && doIt) {
+            // same as:
+            // - EnigmailWindows.openPrefWindow(window, true, 'sendingTab');
+            // but
+            // - without starting the service again because we do that right now
+            // - and modal (waiting for its end)
+            win.openDialog(
+              "chrome://openpgp/content/ui/pref-enigmail.xhtml",
+              "_blank",
+              "chrome,resizable=yes,modal",
+              {
+                showBasic: true,
+                clientType: "thunderbird",
+                selectTab: "sendingTab",
+              }
+            );
+          }
+        }, 100);
       }
 
-      if (vc.compare(oldVer, "1.9a2pre") < 0) {
+      if (Services.vc.compare(oldVer, "1.9a2pre") < 0) {
         defaultPgpMime();
       }
-      if (vc.compare(oldVer, "2.0a1pre") < 0) {
+      if (Services.vc.compare(oldVer, "2.0a1pre") < 0) {
         this.upgradeTo20();
       }
-      if (vc.compare(oldVer, "2.0.1a2pre") < 0) {
+      if (Services.vc.compare(oldVer, "2.0.1a2pre") < 0) {
         this.upgradeTo201();
       }
-      if (vc.compare(oldVer, "2.1b2") < 0) {
+      if (Services.vc.compare(oldVer, "2.1b2") < 0) {
         this.upgradeTo21();
       }
-
     }
 
     EnigmailPrefs.setPref("configuredVersion", EnigmailApp.getVersion());
     EnigmailPrefs.savePrefs();
   },
 
-  upgradeTo20: function() {
+  upgradeTo20() {
     replaceKeyIdWithFpr();
     displayUpgradeInfo();
   },
 
-  upgradeTo201: function() {
+  upgradeTo201() {
     setAutocryptForOldAccounts();
   },
 
-  upgradeTo21: function() {
+  upgradeTo21() {
     setDefaultKeyServer();
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/constants.jsm
+++ b/mail/extensions/openpgp/content/modules/constants.jsm
@@ -1,15 +1,14 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailConstants"];
 
 var EnigmailConstants = {
   POSSIBLE_PGPMIME: -2081,
 
   // possible values for
@@ -157,10 +156,10 @@ var EnigmailConstants = {
   /* Bootstrapped Addon constants */
   APP_STARTUP: 1, // The application is starting up.
   APP_SHUTDOWN: 2, // The application is shutting down.
   ADDON_ENABLE: 3, // The add-on is being enabled.
   ADDON_DISABLE: 4, // The add-on is being disabled. (Also sent during uninstallation)
   ADDON_INSTALL: 5, // The add-on is being installed.
   ADDON_UNINSTALL: 6, // The add-on is being uninstalled.
   ADDON_UPGRADE: 7, // The add-on is being upgraded.
-  ADDON_DOWNGRADE: 8 // The add-on is being downgraded.
+  ADDON_DOWNGRADE: 8, // The add-on is being downgraded.
 };
--- a/mail/extensions/openpgp/content/modules/core.jsm
+++ b/mail/extensions/openpgp/content/modules/core.jsm
@@ -1,74 +1,109 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
-const {
-  manager: Cm,
-  Constructor: CC
-} = Components;
+const { manager: Cm } = Components;
 Cm.QueryInterface(Ci.nsIComponentRegistrar);
 
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
 
 // load all modules lazily to avoid possible cross-reference errors
-const getEnigmailConsole = EnigmailLazy.loader("enigmail/pipeConsole.jsm", "EnigmailConsole");
-const getEnigmailMimeEncrypt = EnigmailLazy.loader("enigmail/mimeEncrypt.jsm", "EnigmailMimeEncrypt");
-const getEnigmailProtocolHandler = EnigmailLazy.loader("enigmail/protocolHandler.jsm", "EnigmailProtocolHandler");
-const getEnigmailFiltersWrapper = EnigmailLazy.loader("enigmail/filtersWrapper.jsm", "EnigmailFiltersWrapper");
+const getEnigmailConsole = EnigmailLazy.loader(
+  "enigmail/pipeConsole.jsm",
+  "EnigmailConsole"
+);
+const getEnigmailMimeEncrypt = EnigmailLazy.loader(
+  "enigmail/mimeEncrypt.jsm",
+  "EnigmailMimeEncrypt"
+);
+const getEnigmailProtocolHandler = EnigmailLazy.loader(
+  "enigmail/protocolHandler.jsm",
+  "EnigmailProtocolHandler"
+);
+const getEnigmailFiltersWrapper = EnigmailLazy.loader(
+  "enigmail/filtersWrapper.jsm",
+  "EnigmailFiltersWrapper"
+);
 const getEnigmailLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
-const getEnigmailOS = EnigmailLazy.loader("enigmail/os.jsm", "EnigmailOS");
-const getEnigmailLocale = EnigmailLazy.loader("enigmail/locale.jsm", "EnigmailLocale");
-const getEnigmailCommandLine = EnigmailLazy.loader("enigmail/commandLine.jsm", "EnigmailCommandLine");
-const getEnigmailPrefs = EnigmailLazy.loader("enigmail/prefs.jsm", "EnigmailPrefs");
-const getEnigmailVerify = EnigmailLazy.loader("enigmail/mimeVerify.jsm", "EnigmailVerify");
-const getEnigmailWindows = EnigmailLazy.loader("enigmail/windows.jsm", "EnigmailWindows");
-const getEnigmailDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
-const getEnigmailConfigure = EnigmailLazy.loader("enigmail/configure.jsm", "EnigmailConfigure");
+const getEnigmailLocale = EnigmailLazy.loader(
+  "enigmail/locale.jsm",
+  "EnigmailLocale"
+);
+const getEnigmailCommandLine = EnigmailLazy.loader(
+  "enigmail/commandLine.jsm",
+  "EnigmailCommandLine"
+);
+const getEnigmailPrefs = EnigmailLazy.loader(
+  "enigmail/prefs.jsm",
+  "EnigmailPrefs"
+);
+const getEnigmailVerify = EnigmailLazy.loader(
+  "enigmail/mimeVerify.jsm",
+  "EnigmailVerify"
+);
+const getEnigmailWindows = EnigmailLazy.loader(
+  "enigmail/windows.jsm",
+  "EnigmailWindows"
+);
+const getEnigmailDialog = EnigmailLazy.loader(
+  "enigmail/dialog.jsm",
+  "EnigmailDialog"
+);
+const getEnigmailConfigure = EnigmailLazy.loader(
+  "enigmail/configure.jsm",
+  "EnigmailConfigure"
+);
 const getEnigmailApp = EnigmailLazy.loader("enigmail/app.jsm", "EnigmailApp");
-const getEnigmailKeyRefreshService = EnigmailLazy.loader("enigmail/keyRefreshService.jsm", "EnigmailKeyRefreshService");
-const getEnigmailKeyServer = EnigmailLazy.loader("enigmail/keyserver.jsm", "EnigmailKeyServer");
-const getEnigmailWksMimeHandler = EnigmailLazy.loader("enigmail/wksMimeHandler.jsm", "EnigmailWksMimeHandler");
+const getEnigmailWksMimeHandler = EnigmailLazy.loader(
+  "enigmail/wksMimeHandler.jsm",
+  "EnigmailWksMimeHandler"
+);
 //const getEnigmailOverlays = EnigmailLazy.loader("enigmail/enigmailOverlays.jsm", "EnigmailOverlays");
-const getEnigmailSqlite = EnigmailLazy.loader("enigmail/sqliteDb.jsm", "EnigmailSqliteDb");
-const getEnigmailTimer = EnigmailLazy.loader("enigmail/timer.jsm", "EnigmailTimer");
-const getOpenPGPMasterpass = EnigmailLazy.loader("enigmail/masterpass.jsm", "OpenPGPMasterpass");
-const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
+const getEnigmailSqlite = EnigmailLazy.loader(
+  "enigmail/sqliteDb.jsm",
+  "EnigmailSqliteDb"
+);
+const getOpenPGPMasterpass = EnigmailLazy.loader(
+  "enigmail/masterpass.jsm",
+  "OpenPGPMasterpass"
+);
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 var EXPORTED_SYMBOLS = ["EnigmailCore"];
 
 // Interfaces
 const nsIEnvironment = Ci.nsIEnvironment;
 
-var gPreferredGpgPath = null;
 var gOverwriteEnvVar = [];
 var gEnigmailService = null; // Global Enigmail Service
 
 var gEnvList = null; // currently filled from enigmail.js
 
 var EnigmailCore = {
   /**
    * Create a new instance of Enigmail, or return the already existing one
    */
-  createInstance: function() {
+  createInstance() {
     if (!gEnigmailService) {
       gEnigmailService = new Enigmail();
     }
 
     return gEnigmailService;
   },
 
-  startup: function(reason) {
+  startup(reason) {
     let self = this;
 
     let env = getEnvironment();
     initializeLogDirectory();
     initializeLogging(env);
 
     const logger = getEnigmailLog();
 
@@ -85,36 +120,51 @@ var EnigmailCore = {
       try {
         let mimeEncrypt = getEnigmailMimeEncrypt();
         mimeEncrypt.startup(reason);
         //getEnigmailOverlays().startup();
         self.factories.push(new Factory(getEnigmailProtocolHandler()));
         self.factories.push(new Factory(mimeEncrypt.Handler));
         getOpenPGPMasterpass().ensureMasterPassword();
       } catch (ex) {
-        Services.console.logStringMessage("core.jsm: startup.continueStartup: error " + ex.message + "\n" + ex.stack + "\n");
-        logger.DEBUG("core.jsm: startup.continueStartup: error " + ex.message + "\n" + ex.stack + "\n");
+        Services.console.logStringMessage(
+          "core.jsm: startup.continueStartup: error " +
+            ex.message +
+            "\n" +
+            ex.stack +
+            "\n"
+        );
+        logger.DEBUG(
+          "core.jsm: startup.continueStartup: error " +
+            ex.message +
+            "\n" +
+            ex.stack +
+            "\n"
+        );
       }
     }
 
     getEnigmailVerify().registerContentTypeHandler();
     getEnigmailWksMimeHandler().registerContentTypeHandler();
     getEnigmailFiltersWrapper().onStartup();
     continueStartup(1);
 
     let myName = getEnigmailLocale().getString("Enigmail");
     console.log("core.jsm: loaded string from properties " + myName);
   },
 
-  shutdown: function(reason) {
+  shutdown(reason) {
     getEnigmailLog().DEBUG("core.jsm: shutdown():\n");
 
     let cLineReg = getEnigmailCommandLine().categoryRegistry;
-    let catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
-    catMan.deleteCategoryEntry(cLineReg.category, cLineReg.entry, false);
+    Services.catMan.deleteCategoryEntry(
+      cLineReg.category,
+      cLineReg.entry,
+      false
+    );
 
     if (this.factories) {
       for (let fct of this.factories) {
         fct.unregister();
       }
     }
 
     getEnigmailFiltersWrapper().onShutdown();
@@ -124,138 +174,183 @@ var EnigmailCore = {
     getEnigmailLog().onShutdown();
 
     getEnigmailLog().setLogLevel(3);
     gEnigmailService = null;
   },
 
   version: "",
 
-  init: function(enigmailVersion) {
+  init(enigmailVersion) {
     this.version = enigmailVersion;
   },
 
   /**
    * get and or initialize the Enigmail service,
    * including the handling for upgrading old preferences to new versions
    *
    * @win:                - nsIWindow: parent window (optional)
    * @startingPreferences - Boolean: true - called while switching to new preferences
    *                        (to avoid re-check for preferences)
    */
-  getService: function(win, startingPreferences) {
+  getService(win, startingPreferences) {
     // Lazy initialization of Enigmail JS component (for efficiency)
 
     if (gEnigmailService) {
       return gEnigmailService.initialized ? gEnigmailService : null;
     }
 
     try {
       this.createInstance();
       return gEnigmailService.getService(win, startingPreferences);
     } catch (ex) {
       return null;
     }
-
   },
 
-  getEnigmailService: function() {
+  getEnigmailService() {
     return gEnigmailService;
   },
 
-  setEnigmailService: function(v) {
+  setEnigmailService(v) {
     gEnigmailService = v;
   },
 
   /**
    * obtain a list of all environment variables
    *
    * @return: Array of Strings with the following structrue
    *          variable_name=variable_content
    */
-  getEnvList: function() {
+  getEnvList() {
     return gEnvList;
   },
 
-  addToEnvList: function(str) {
+  addToEnvList(str) {
     gEnvList.push(str);
   },
 
-  setEnvVariable: function(varname, value) {
+  setEnvVariable(varname, value) {
     for (let i = 0; i < gEnvList.length; i++) {
       if (gEnvList[i].startsWith(varname + "=")) {
         gEnvList[i] = varname + "=" + value;
         break;
       }
     }
-  }
+  },
 };
 
 ///////////////////////////////////////////////////////////////////////////////
 // Enigmail encryption/decryption service
 ///////////////////////////////////////////////////////////////////////////////
 
 function getLogDirectoryPrefix() {
   try {
-    return getEnigmailPrefs().getPrefBranch().getCharPref("logDirectory") || "";
+    return (
+      getEnigmailPrefs()
+        .getPrefBranch()
+        .getCharPref("logDirectory") || ""
+    );
   } catch (ex) {
     return "";
   }
 }
 
 function initializeLogDirectory() {
   const prefix = getLogDirectoryPrefix();
   if (prefix) {
     getEnigmailLog().setLogLevel(5);
     getEnigmailLog().setLogDirectory(prefix);
-    getEnigmailLog().DEBUG("core.jsm: Logging debug output to " + prefix + "/enigdbug.txt\n");
+    getEnigmailLog().DEBUG(
+      "core.jsm: Logging debug output to " + prefix + "/enigdbug.txt\n"
+    );
   }
 }
 
 function initializeLogging(env) {
   const nspr_log_modules = env.get("NSPR_LOG_MODULES");
   const matches = nspr_log_modules.match(/enigmail.js:(\d+)/);
 
-  if (matches && (matches.length > 1)) {
+  if (matches && matches.length > 1) {
     getEnigmailLog().setLogLevel(Number(matches[1]));
-    getEnigmailLog().WARNING("core.jsm: Enigmail: LogLevel=" + matches[1] + "\n");
+    getEnigmailLog().WARNING(
+      "core.jsm: Enigmail: LogLevel=" + matches[1] + "\n"
+    );
   }
 }
 
 function failureOn(ex, status) {
-  status.initializationError = getEnigmailLocale().getString("enigmailNotAvailable");
-  getEnigmailLog().ERROR("core.jsm: Enigmail.initialize: Error - " + status.initializationError + "\n");
-  getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: exception=" + ex.toString() + "\n");
-  throw Components.results.NS_ERROR_FAILURE;
+  status.initializationError = getEnigmailLocale().getString(
+    "enigmailNotAvailable"
+  );
+  getEnigmailLog().ERROR(
+    "core.jsm: Enigmail.initialize: Error - " +
+      status.initializationError +
+      "\n"
+  );
+  getEnigmailLog().DEBUG(
+    "core.jsm: Enigmail.initialize: exception=" + ex.toString() + "\n"
+  );
+  throw Cr.NS_ERROR_FAILURE;
 }
 
 function getEnvironment(status) {
   try {
     return Cc["@mozilla.org/process/environment;1"].getService(nsIEnvironment);
   } catch (ex) {
     failureOn(ex, status);
   }
   return null;
 }
 
 function initializeEnvironment(env) {
   // Initialize global environment variables list
-  let passEnv = ["GNUPGHOME", "GPGDIR", "ETC",
-    "ALLUSERSPROFILE", "APPDATA", "LOCALAPPDATA", "BEGINLIBPATH",
-    "COMMONPROGRAMFILES", "COMSPEC", "DBUS_SESSION_BUS_ADDRESS", "DISPLAY",
-    "ENIGMAIL_PASS_ENV", "ENDLIBPATH",
+  let passEnv = [
+    "GNUPGHOME",
+    "GPGDIR",
+    "ETC",
+    "ALLUSERSPROFILE",
+    "APPDATA",
+    "LOCALAPPDATA",
+    "BEGINLIBPATH",
+    "COMMONPROGRAMFILES",
+    "COMSPEC",
+    "DBUS_SESSION_BUS_ADDRESS",
+    "DISPLAY",
+    "ENIGMAIL_PASS_ENV",
+    "ENDLIBPATH",
     "GTK_IM_MODULE",
-    "HOME", "HOMEDRIVE", "HOMEPATH",
-    "LOCPATH", "LOGNAME", "LD_LIBRARY_PATH", "MOZILLA_FIVE_HOME",
-    "NLSPATH", "PATH", "PATHEXT", "PINENTRY_USER_DATA", "PROGRAMFILES", "PWD",
+    "HOME",
+    "HOMEDRIVE",
+    "HOMEPATH",
+    "LOCPATH",
+    "LOGNAME",
+    "LD_LIBRARY_PATH",
+    "MOZILLA_FIVE_HOME",
+    "NLSPATH",
+    "PATH",
+    "PATHEXT",
+    "PINENTRY_USER_DATA",
+    "PROGRAMFILES",
+    "PWD",
     "QT_IM_MODULE",
-    "SHELL", "SYSTEMDRIVE", "SYSTEMROOT",
-    "TEMP", "TMP", "TMPDIR", "TZ", "TZDIR", "UNIXROOT",
-    "USER", "USERPROFILE", "WINDIR", "XAUTHORITY",
-    "XMODIFIERS"
+    "SHELL",
+    "SYSTEMDRIVE",
+    "SYSTEMROOT",
+    "TEMP",
+    "TMP",
+    "TMPDIR",
+    "TZ",
+    "TZDIR",
+    "UNIXROOT",
+    "USER",
+    "USERPROFILE",
+    "WINDIR",
+    "XAUTHORITY",
+    "XMODIFIERS",
   ];
 
   gEnvList = [];
 
   // if (!getEnigmailPrefs().getPref("gpgLocaleEn")) {
   //   passEnv = passEnv.concat([
   //     "LANG", "LANGUAGE", "LC_ALL", "LC_COLLATE", "LC_CTYPE",
   //     "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME"
@@ -287,35 +382,38 @@ function initializeEnvironment(env) {
     } else {
       envValue = env.get(envName);
     }
     if (envValue) {
       EnigmailCore.addToEnvList(envName + "=" + envValue);
     }
   }
 
-  getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: Ec.envList = " + gEnvList + "\n");
+  getEnigmailLog().DEBUG(
+    "core.jsm: Enigmail.initialize: Ec.envList = " + gEnvList + "\n"
+  );
 }
 
-
 function Enigmail() {
   this.wrappedJSObject = this;
 }
 
 Enigmail.prototype = {
   initialized: false,
   initializationAttempted: false,
   initializationError: "",
 
-  initialize: function(domWindow, version) {
+  initialize(domWindow, version) {
     this.initializationAttempted = true;
 
     getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: START\n");
 
-    if (this.initialized) return;
+    if (this.initialized) {
+      return;
+    }
 
     this.environment = getEnvironment(this);
 
     initializeEnvironment(this.environment);
 
     try {
       getEnigmailConsole().write("Initializing Enigmail service ...\n");
     } catch (ex) {
@@ -324,76 +422,82 @@ Enigmail.prototype = {
 
     //getEnigmailKeyRefreshService().start(getEnigmailKeyServer());
 
     this.initialized = true;
 
     getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: END\n");
   },
 
-  reinitialize: function() {
+  reinitialize() {
     getEnigmailLog().DEBUG("core.jsm: Enigmail.reinitialize:\n");
     this.initialized = false;
     this.initializationAttempted = true;
 
     getEnigmailConsole().write("Reinitializing Enigmail service ...\n");
     initializeEnvironment(this.environment);
     this.initialized = true;
   },
 
-  perferGpgPath: function(gpgPath) {
-    getEnigmailLog().DEBUG("core.jsm: Enigmail.perferGpgPath = " + gpgPath + "\n");
-    gPreferredGpgPath = gpgPath;
-  },
-
-  overwriteEnvVar: function(envVar) {
+  overwriteEnvVar(envVar) {
     let envLines = envVar.split(/\n/);
 
     gOverwriteEnvVar = [];
     for (let i = 0; i < envLines.length; i++) {
       let j = envLines[i].indexOf("=");
       if (j > 0) {
         gOverwriteEnvVar[envLines[i].substr(0, j)] = envLines[i].substr(j + 1);
       }
     }
   },
 
-  getService: function(win, startingPreferences) {
+  getService(win, startingPreferences) {
     if (!win) {
       win = getEnigmailWindows().getBestParentWin();
     }
 
     getEnigmailLog().DEBUG("core.jsm: svc = " + this + "\n");
 
     if (!this.initialized) {
       const firstInitialization = !this.initializationAttempted;
 
       try {
         // Initialize enigmail
         EnigmailCore.init(getEnigmailApp().getVersion());
         this.initialize(win, getEnigmailApp().getVersion());
 
         try {
           // Reset alert count to default value
-          getEnigmailPrefs().getPrefBranch().clearUserPref("initAlert");
+          getEnigmailPrefs()
+            .getPrefBranch()
+            .clearUserPref("initAlert");
         } catch (ex) {}
       } catch (ex) {
         if (firstInitialization) {
           // Display initialization error alert
-          const errMsg = (this.initializationError ? this.initializationError : getEnigmailLocale().getString("accessError")) +
-            "\n\n" + getEnigmailLocale().getString("initErr.howToFixIt");
+          const errMsg =
+            (this.initializationError
+              ? this.initializationError
+              : getEnigmailLocale().getString("accessError")) +
+            "\n\n" +
+            getEnigmailLocale().getString("initErr.howToFixIt");
 
           const checkedObj = {
-            value: false
+            value: false,
           };
           if (getEnigmailPrefs().getPref("initAlert")) {
-            const r = getEnigmailDialog().longAlert(win, "Enigmail: " + errMsg,
+            const r = getEnigmailDialog().longAlert(
+              win,
+              "Enigmail: " + errMsg,
               getEnigmailLocale().getString("dlgNoPrompt"),
-              null, getEnigmailLocale().getString("initErr.setupWizard.button"),
-              null, checkedObj);
+              null,
+              getEnigmailLocale().getString("initErr.setupWizard.button"),
+              null,
+              checkedObj
+            );
             if (r >= 0 && checkedObj.value) {
               getEnigmailPrefs().setPref("initAlert", false);
             }
             if (r == 1) {
               // start setup wizard
               getEnigmailWindows().openSetupWizard(win, false);
               return Enigmail.getService(win);
             }
@@ -404,45 +508,51 @@ Enigmail.prototype = {
           }
         }
 
         return null;
       }
 
       const configuredVersion = getEnigmailPrefs().getPref("configuredVersion");
 
-      getEnigmailLog().DEBUG("core.jsm: getService: last used version: " + configuredVersion + "\n");
+      getEnigmailLog().DEBUG(
+        "core.jsm: getService: last used version: " + configuredVersion + "\n"
+      );
 
-      if (this.initialized && (getEnigmailApp().getVersion() != configuredVersion)) {
+      if (
+        this.initialized &&
+        getEnigmailApp().getVersion() != configuredVersion
+      ) {
         getEnigmailConfigure().configureEnigmail(win, startingPreferences);
       }
     }
 
     return this.initialized ? this : null;
-  }
+  },
 }; // Enigmail.prototype
 
-
 class Factory {
   constructor(component) {
     this.component = component;
     this.register();
     Object.freeze(this);
   }
 
   createInstance(outer, iid) {
     if (outer) {
       throw Cr.NS_ERROR_NO_AGGREGATION;
     }
     return new this.component();
   }
 
   register() {
-    Cm.registerFactory(this.component.prototype.classID,
+    Cm.registerFactory(
+      this.component.prototype.classID,
       this.component.prototype.classDescription,
       this.component.prototype.contractID,
-      this);
+      this
+    );
   }
 
   unregister() {
     Cm.unregisterFactory(this.component.prototype.classID, this);
   }
 }
--- a/mail/extensions/openpgp/content/modules/cryptoAPI.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI.jsm
@@ -1,33 +1,32 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
-var EXPORTED_SYMBOLS = ["EnigmailCryptoAPI"];
+var EXPORTED_SYMBOLS = ["EnigmailCryptoAPI", "EnigmailGnuPGAPI"];
 
 var gCurrentApi = null;
 var gGnuPGApi = null;
-var Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
 
 function EnigmailCryptoAPI() {
   if (!gCurrentApi) {
-    const {
-      getRNPAPI
-    } = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm");
+    const { getRNPAPI } = ChromeUtils.import(
+      "chrome://openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm"
+    );
     gCurrentApi = getRNPAPI();
   }
   return gCurrentApi;
 }
 
 function EnigmailGnuPGAPI() {
   if (!gGnuPGApi) {
-    const {
-      getGnuPGAPI
-    } = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm");
+    const { getGnuPGAPI } = ChromeUtils.import(
+      "chrome://openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm"
+    );
     gGnuPGApi = getGnuPGAPI();
   }
   return gGnuPGApi;
 }
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm
@@ -1,47 +1,48 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["getGnuPGAPI"];
 
-var Services = Components.utils.import("resource://gre/modules/Services.jsm").Services;
+var Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-Services.scriptloader.loadSubScript("chrome://openpgp/content/modules/cryptoAPI/interface.js",
-  null, "UTF-8"); /* global CryptoAPI */
-
-/* global getOpenPGP: false, EnigmailLog: false */
+Services.scriptloader.loadSubScript(
+  "chrome://openpgp/content/modules/cryptoAPI/interface.js",
+  null,
+  "UTF-8"
+); /* global CryptoAPI */
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailErrorHandling = ChromeUtils.import("chrome://openpgp/content/modules/errorHandling.jsm").EnigmailErrorHandling;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
 
 const {
   obtainKeyList,
   getPhotoFileFromGnuPG,
-  extractSignatures,
-  getGpgKeyData
-} = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm");
+  getGpgKeyData,
+} = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm"
+);
 
-const {
-  GnuPG_importKeyFromFile,
-  GnuPG_extractSecretKey
-} = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/gnupg-key.jsm");
+const { GnuPG_importKeyFromFile, GnuPG_extractSecretKey } = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI/gnupg-key.jsm"
+);
 
 /**
  * GnuPG implementation of CryptoAPI
  */
 
 class GnuPGCryptoAPI extends CryptoAPI {
   constructor() {
     super();
@@ -67,17 +68,16 @@ class GnuPGCryptoAPI extends CryptoAPI {
    *
    * @return {Promise<Array of Object>} - see extractSignatures()
    */
   async getKeySignatures(keyId, ignoreUnknownUid = false) {
     EnigmailLog.DEBUG(`gnupg.js: getKeySignatures: ${keyId}\n`);
     throw new Error("Not implemented");
   }
 
-
   /**
    * Export the minimum key for the public key object:
    * public key, primary user ID, newest encryption subkey
    *
    * @param {String} fpr:                a single FPR
    * @param {String} email:              [optional] the email address of the desired user ID.
    *                                     If the desired user ID cannot be found or is not valid, use the primary UID instead
    * @param {Array<Number>} subkeyDates: [optional] remove subkeys with sepcific creation Dates
@@ -137,17 +137,18 @@ class GnuPGCryptoAPI extends CryptoAPI {
    *   - {String} keyData:   ASCII armored key data material
    *   - {String} errorMsg:  error message in case exitCode !== 0
    */
 
   async extractSecretKey(keyId, minimalKey) {
     let ret = await GnuPG_extractSecretKey(keyId, minimalKey);
 
     if (ret.exitCode !== 0) {
-      ret.errorMsg = EnigmailLocale.getString("failKeyExtract") + "\n" + ret.errorMsg;
+      ret.errorMsg =
+        EnigmailLocale.getString("failKeyExtract") + "\n" + ret.errorMsg;
     }
     return ret;
   }
 
   /**
    *
    * @param {byte} byteData    The encrypted data
    *
@@ -170,34 +171,32 @@ class GnuPGCryptoAPI extends CryptoAPI {
    * The message will be an error message in this case.
    */
 
   async verifyAttachment(filePath, sigPath) {
     EnigmailLog.DEBUG(`gnupg.js: verifyAttachment()\n`);
     throw new Error("Not implemented");
   }
 
-
   /**
    *
    * @param {Bytes}  encrypted     The encrypted data
    *
    * @return {Promise<Object>} - Return object with decryptedData and
    * status information
    *
    * Use Promise.catch to handle failed decryption.
    * retObj.errorMsg will be an error message in this case.
    */
 
   async decryptAttachment(encrypted) {
     EnigmailLog.DEBUG(`gnupg.js: decryptAttachment()\n`);
     throw new Error("Not implemented");
   }
 
-
   /**
    *
    * @param {String} encrypted     The encrypted data
    * @param {Object} options       Decryption options
    *
    * @return {Promise<Object>} - Return object with decryptedData and
    * status information
    *
@@ -262,17 +261,16 @@ class GnuPGCryptoAPI extends CryptoAPI {
   async getKeyListFromKeyBlock(keyBlockStr) {
     let res;
     res = await getGpgKeyData(keyBlockStr);
     return res;
   }
 
   async genKey(userId, keyType, keySize, expiryTime, passphrase) {
     throw new Error("GnuPG genKey() not implemented");
-    return null;
   }
 
   async deleteKey(keyFingerprint, deleteSecret) {
     return null;
   }
 
   async encryptAndOrSign(plaintext, args, resultStatus) {
     return null;
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm
@@ -11,39 +11,24 @@ var EXPORTED_SYMBOLS = ["getRNPAPI"];
 const RNP = ChromeUtils.import("chrome://openpgp/content/modules/rnp.jsm").RNP;
 var Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
   .Services;
 
 Services.scriptloader.loadSubScript(
   "chrome://openpgp/content/modules/cryptoAPI/interface.js",
   null,
   "UTF-8"
-);
-
-/* Globals loaded from openpgp-js.js: */
-/* global getOpenPGP: false, EnigmailLog: false */
+); /* global CryptoAPI */
 
 const EnigmailLog = ChromeUtils.import(
   "chrome://openpgp/content/modules/log.jsm"
 ).EnigmailLog;
-const EnigmailFiles = ChromeUtils.import(
-  "chrome://openpgp/content/modules/files.jsm"
-).EnigmailFiles;
 const EnigmailConstants = ChromeUtils.import(
   "chrome://openpgp/content/modules/constants.jsm"
 ).EnigmailConstants;
-const EnigmailTime = ChromeUtils.import(
-  "chrome://openpgp/content/modules/time.jsm"
-).EnigmailTime;
-const EnigmailData = ChromeUtils.import(
-  "chrome://openpgp/content/modules/data.jsm"
-).EnigmailData;
-const EnigmailLocale = ChromeUtils.import(
-  "chrome://openpgp/content/modules/locale.jsm"
-).EnigmailLocale;
 
 /**
  * RNP implementation of CryptoAPI
  */
 
 class RNPCryptoAPI extends CryptoAPI {
   constructor() {
     super();
@@ -259,25 +244,25 @@ class RNPCryptoAPI extends CryptoAPI {
     return RNP.getKeyListFromKeyBlock(keyBlockStr);
   }
 
   async genKey(userId, keyType, keySize, expiryTime, passphrase) {
     let id = RNP.genKey(userId, keyType, keySize, expiryTime, passphrase);
     RNP.saveKeyRings();
     return id;
   }
-  
+
   async deleteKey(keyFingerprint, deleteSecret) {
-    return RNP.deleteKey(keyId, deleteSecret);
+    return RNP.deleteKey(keyFingerprint, deleteSecret);
   }
 
   async encryptAndOrSign(plaintext, args, resultStatus) {
     return RNP.encryptAndOrSign(plaintext, args, resultStatus);
   }
-  
+
   async getPublicKey(id) {
     return RNP.getPublicKey(id);
   }
 }
 
 function getRNPAPI() {
   return new RNPCryptoAPI();
 }
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-key.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-key.jsm
@@ -7,20 +7,22 @@
 /****
    Private sub-module to GnuPGCryptoAPI.jsm for handling key import/export
  ****/
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["GnuPG_importKeyFromFile", "GnuPG_extractSecretKey"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
 
 async function GnuPG_importKeyFromFile(inputFile) {
-  EnigmailLog.DEBUG("gnupg-key.jsm: importKeysFromFile: fileName=" + inputFile.path + "\n");
+  EnigmailLog.DEBUG(
+    "gnupg-key.jsm: importKeysFromFile: fileName=" + inputFile.path + "\n"
+  );
   throw new Error("Not implemented");
 }
 
-
 async function GnuPG_extractSecretKey(userId, minimalKey) {
   throw new Error("Not implemented");
 }
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm
@@ -5,28 +5,38 @@
  */
 
 /****
    Private sub-module to GnuPGCryptoAPI.jsm for handling key lists from GnuPG
  ****/
 
 "use strict";
 
-var EXPORTED_SYMBOLS = ["obtainKeyList",
-  "getPhotoFileFromGnuPG", "extractSignatures", "getGpgKeyData"
+var EXPORTED_SYMBOLS = [
+  "obtainKeyList",
+  "getPhotoFileFromGnuPG",
+  "extractSignatures",
+  "getGpgKeyData",
 ];
 
-const EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailTrust = ChromeUtils.import("chrome://openpgp/content/modules/trust.jsm").EnigmailTrust;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
+const EnigmailTime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/time.jsm"
+).EnigmailTime;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailTrust = ChromeUtils.import(
+  "chrome://openpgp/content/modules/trust.jsm"
+).EnigmailTrust;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
 
 // field ID's of key list (as described in the doc/DETAILS file in the GnuPG distribution)
 const ENTRY_ID = 0;
 const KEY_TRUST_ID = 1;
 const KEY_SIZE_ID = 2;
 const KEY_ALGO_ID = 3;
 const KEY_ID = 4;
 const CREATED_ID = 5;
@@ -41,43 +51,34 @@ const ALGO_SYMBOL = {
   1: "RSA",
   2: "RSA",
   3: "RSA",
   16: "ELG",
   17: "DSA",
   18: "ECDH",
   19: "ECDSA",
   20: "ELG",
-  22: "EDDSA"
+  22: "EDDSA",
 };
 
 const UNKNOWN_SIGNATURE = "[User ID not found]";
 
-const NS_RDONLY = 0x01;
-const NS_WRONLY = 0x02;
-const NS_CREATE_FILE = 0x08;
-const NS_TRUNCATE = 0x20;
-const STANDARD_FILE_PERMS = 0o600;
-
-const NS_LOCALFILEOUTPUTSTREAM_CONTRACTID = "@mozilla.org/network/file-output-stream;1";
-
 /**
  * Get key list from GnuPG.
  *
  * @param {Array of String} onlyKeys: only load data for specified key IDs
  *
  * @return {Promise<Array Object>}:
  * key objects as specified in EnigmailKeyObj.constructor
  */
 async function obtainKeyList(onlyKeys = null) {
   EnigmailLog.DEBUG("gnupg-keylist.jsm: obtainKeyList()\n");
   throw new Error("Not implemented");
 }
 
-
 /**
  * Append key objects to a given key cache
  *
  * @param keyListString: array of |string| formatted output from GnuPG for key listing
  * @param keyList:    |object| holding the resulting key list
  *                         obj.keyList:     Array holding key objects
  *                         obj.keySortList: Array holding values to make sorting easier
  *
@@ -87,17 +88,19 @@ function appendKeyItems(keyListString, k
   EnigmailLog.DEBUG("gnupg-keylist.jsm: appendKeyItems()\n");
   let keyObj = {};
   let uatNum = 0; // counter for photos (counts per key)
 
   const TRUSTLEVELS_SORTED = EnigmailTrust.trustLevelsSorted();
 
   for (let i = 0; i < keyListString.length; i++) {
     let listRow = keyListString[i].split(/:/);
-    if (listRow.length === 0) continue;
+    if (listRow.length === 0) {
+      continue;
+    }
 
     switch (listRow[ENTRY_ID]) {
       case "pub":
         keyObj = createKeyObj(listRow);
         uatNum = 0;
         keyList.keys.push(keyObj);
         keyList.index[keyObj.keyId] = keyObj;
         break;
@@ -118,55 +121,58 @@ function appendKeyItems(keyListString, k
         if (keyObj.fpr === "") {
           keyObj.fpr = listRow[USERID_ID];
         }
         break;
       case "uid":
         if (listRow[USERID_ID].length === 0) {
           listRow[USERID_ID] = "-";
         }
-        if (typeof(keyObj.userId) !== "string") {
+        if (typeof keyObj.userId !== "string") {
           keyObj.userId = EnigmailData.convertGpgToUnicode(listRow[USERID_ID]);
-          if (TRUSTLEVELS_SORTED.indexOf(listRow[KEY_TRUST_ID]) < TRUSTLEVELS_SORTED.indexOf(keyObj.keyTrust)) {
+          if (
+            TRUSTLEVELS_SORTED.indexOf(listRow[KEY_TRUST_ID]) <
+            TRUSTLEVELS_SORTED.indexOf(keyObj.keyTrust)
+          ) {
             // reduce key trust if primary UID is less trusted than public key
             keyObj.keyTrust = listRow[KEY_TRUST_ID];
           }
         }
 
         keyObj.userIds.push({
           userId: EnigmailData.convertGpgToUnicode(listRow[USERID_ID]),
           keyTrust: listRow[KEY_TRUST_ID],
           uidFpr: listRow[UID_ID],
-          type: "uid"
+          type: "uid",
         });
 
         break;
       case "sub":
         keyObj.subKeys.push({
           keyId: listRow[KEY_ID],
           expiry: EnigmailTime.getDateTime(listRow[EXPIRY_ID], true, false),
           expiryTime: Number(listRow[EXPIRY_ID]),
           keyTrust: listRow[KEY_TRUST_ID],
           keyUseFor: listRow[KEY_USE_FOR_ID],
           keySize: listRow[KEY_SIZE_ID],
           algoSym: ALGO_SYMBOL[listRow[KEY_ALGO_ID]],
           created: EnigmailTime.getDateTime(listRow[CREATED_ID], true, false),
           keyCreated: Number(listRow[CREATED_ID]),
-          type: "sub"
+          type: "sub",
         });
         break;
       case "uat":
         if (listRow[USERID_ID].indexOf("1 ") === 0) {
           const userId = EnigmailLocale.getString("userAtt.photo");
           keyObj.userIds.push({
-            userId: userId,
+            userId,
             keyTrust: listRow[KEY_TRUST_ID],
             uidFpr: listRow[UID_ID],
             type: "uat",
-            uatNum: uatNum
+            uatNum,
           });
           keyObj.photoAvailable = true;
           ++uatNum;
         }
         break;
     }
   }
 }
@@ -193,50 +199,56 @@ function createKeyObj(lineArr) {
     keyObj.userIds = [];
     keyObj.subKeys = [];
   }
   keyObj.type = lineArr[ENTRY_ID];
 
   return keyObj;
 }
 
-
 /**
  * Handle secret keys for which gpg 2.0 does not create a public key record
  */
 function appendUnkownSecretKey(keyId, aKeyList, startIndex, keyList) {
-  EnigmailLog.DEBUG(`gnupg-keylist.jsm: appendUnkownSecretKey: keyId: ${keyId}\n`);
+  EnigmailLog.DEBUG(
+    `gnupg-keylist.jsm: appendUnkownSecretKey: keyId: ${keyId}\n`
+  );
 
   let keyListStr = [];
 
-  for (let j = startIndex; j < aKeyList.length && (j === startIndex || aKeyList[j].substr(0, 4) !== "sec:"); j++) {
+  for (
+    let j = startIndex;
+    j < aKeyList.length &&
+    (j === startIndex || aKeyList[j].substr(0, 4) !== "sec:");
+    j++
+  ) {
     keyListStr.push(aKeyList[j]);
   }
 
   // make the listing a "public" key
   keyListStr[0] = keyListStr[0].replace(/^sec:/, "pub:");
 
   appendKeyItems(keyListStr, keyList);
 }
 
-
 /**
  * Extract a photo ID from a key, store it as file and return the file object.
  
  * @param {String} keyId:       Key ID / fingerprint
  * @param {Number} photoNumber: number of the photo on the key, starting with 0
  *
  * @return {Promise<nsIFile>} object or null in case no data / error.
  */
 async function getPhotoFileFromGnuPG(keyId, photoNumber) {
-  EnigmailLog.DEBUG(`gnupg-keylist.jsm: getPhotoFileFromGnuPG, keyId=${keyId} photoNumber=${photoNumber}\n`);
+  EnigmailLog.DEBUG(
+    `gnupg-keylist.jsm: getPhotoFileFromGnuPG, keyId=${keyId} photoNumber=${photoNumber}\n`
+  );
   throw new Error("Not implemented");
 }
 
-
 /**
  * Return signatures for a given key list
  *
  * @param {String} gpgKeyList         Output from gpg such as produced by getKeySig()
  *                                    Only the first public key is processed!
  * @param {Boolean} ignoreUnknownUid  true if unknown signer's UIDs should be filtered out
  *
  * @return {Array of Object}:
@@ -271,41 +283,53 @@ function extractSignatures(gpgKeyList, i
       case "pub":
         if (havePub) {
           return listObj;
         }
         havePub = true;
         keyId = lineTokens[KEY_ID];
         break;
       case "fpr":
-        if (fpr === "")
+        if (fpr === "") {
           fpr = lineTokens[USERID_ID];
+        }
         break;
       case "uid":
       case "uat":
         currUid = lineTokens[UID_ID];
         listObj[currUid] = {
-          userId: lineTokens[ENTRY_ID] == "uat" ? EnigmailLocale.getString("keyring.photo") : EnigmailData.convertGpgToUnicode(lineTokens[USERID_ID]),
+          userId:
+            lineTokens[ENTRY_ID] == "uat"
+              ? EnigmailLocale.getString("keyring.photo")
+              : EnigmailData.convertGpgToUnicode(lineTokens[USERID_ID]),
           rawUserId: lineTokens[USERID_ID],
-          keyId: keyId,
-          fpr: fpr,
-          created: EnigmailTime.getDateTime(lineTokens[CREATED_ID], true, false),
-          sigList: []
+          keyId,
+          fpr,
+          created: EnigmailTime.getDateTime(
+            lineTokens[CREATED_ID],
+            true,
+            false
+          ),
+          sigList: [],
         };
         break;
       case "sig":
         if (lineTokens[SIG_TYPE_ID].substr(0, 2).toLowerCase() !== "1f") {
           // ignrore revoked signature
 
           let sig = {
             userId: EnigmailData.convertGpgToUnicode(lineTokens[USERID_ID]),
-            created: EnigmailTime.getDateTime(lineTokens[CREATED_ID], true, false),
+            created: EnigmailTime.getDateTime(
+              lineTokens[CREATED_ID],
+              true,
+              false
+            ),
             signerKeyId: lineTokens[KEY_ID],
             sigType: lineTokens[SIG_TYPE_ID],
-            sigKnown: lineTokens[USERID_ID] != UNKNOWN_SIGNATURE
+            sigKnown: lineTokens[USERID_ID] != UNKNOWN_SIGNATURE,
           };
 
           if (!ignoreUnknownUid || sig.userId != UNKNOWN_SIGNATURE) {
             listObj[currUid].sigList.push(sig);
           }
         }
         break;
     }
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/interface.js
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/interface.js
@@ -28,31 +28,35 @@ class CryptoAPI {
    * @param {Promise} promise: the promise to wait for
    *
    * @return {Variant} whatever the promise returns
    */
   sync(promise) {
     console.log("CryptoAPI.sync() starting");
 
     if (!inspector) {
-      inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+      inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+        Ci.nsIJSInspector
+      );
     }
 
     let res = null;
-    let p = promise.then(gotResult => {
-      console.log("CryptoAPI.sync() good result:");
-      console.log(gotResult);
-      res = gotResult;
-      inspector.exitNestedEventLoop();
-    }).catch(gotResult => {
-      console.log("CryptoAPI.sync() failed result:");
-      console.log(gotResult);
-      res = gotResult;
-      inspector.exitNestedEventLoop();
-    });
+    promise
+      .then(gotResult => {
+        console.log("CryptoAPI.sync() good result:");
+        console.log(gotResult);
+        res = gotResult;
+        inspector.exitNestedEventLoop();
+      })
+      .catch(gotResult => {
+        console.log("CryptoAPI.sync() failed result:");
+        console.log(gotResult);
+        res = gotResult;
+        inspector.exitNestedEventLoop();
+      });
 
     inspector.enterNestedEventLoop(0);
 
     console.log("CryptoAPI.sync() leaving");
     return res;
   }
 
   /**
@@ -79,17 +83,17 @@ class CryptoAPI {
    *    - exitCode (0 = success)
    *    - errorMsg (if exitCode != 0)
    *    - keyData: BASE64-encded string of key data
    */
   async getMinimalPubKey(fpr, email) {
     return {
       exitCode: -1,
       errorMsg: "",
-      keyData: ""
+      keyData: "",
     };
   }
 
   /**
    * Get the list of all konwn keys (including their secret keys)
    * @param {Array of String} onlyKeys: [optional] only load data for specified key IDs
    *
    * @return {Promise<Array of Object>}
--- a/mail/extensions/openpgp/content/modules/data.jsm
+++ b/mail/extensions/openpgp/content/modules/data.jsm
@@ -1,168 +1,181 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailData"];
 
-const SCRIPTABLEUNICODECONVERTER_CONTRACTID = "@mozilla.org/intl/scriptableunicodeconverter";
+const SCRIPTABLEUNICODECONVERTER_CONTRACTID =
+  "@mozilla.org/intl/scriptableunicodeconverter";
 
 const HEX_TABLE = "0123456789abcdef";
 
 function converter(charset) {
-  let unicodeConv = Cc[SCRIPTABLEUNICODECONVERTER_CONTRACTID].getService(Ci.nsIScriptableUnicodeConverter);
+  let unicodeConv = Cc[SCRIPTABLEUNICODECONVERTER_CONTRACTID].getService(
+    Ci.nsIScriptableUnicodeConverter
+  );
   unicodeConv.charset = charset || "utf-8";
   return unicodeConv;
 }
 
 var EnigmailData = {
-  getUnicodeData: function(data) {
+  getUnicodeData(data) {
     // convert output to Unicode
-    var tmpStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
+    var tmpStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
+      Ci.nsIStringInputStream
+    );
     tmpStream.setData(data, data.length);
-    var inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
+    var inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+      Ci.nsIScriptableInputStream
+    );
     inStream.init(tmpStream);
     return inStream.read(tmpStream.available());
   },
 
-  extractMessageId: function(uri) {
+  extractMessageId(uri) {
     var messageId = "";
 
     var matches = uri.match(/^enigmail:message\/(.+)/);
 
-    if (matches && (matches.length > 1)) {
+    if (matches && matches.length > 1) {
       messageId = matches[1];
     }
 
     return messageId;
   },
 
-  extractMimeMessageId: function(uri) {
+  extractMimeMessageId(uri) {
     var messageId = "";
 
     var matches = uri.match(/^enigmail:mime-message\/(.+)/);
 
-    if (matches && (matches.length > 1)) {
+    if (matches && matches.length > 1) {
       messageId = matches[1];
     }
 
     return messageId;
   },
 
-  decodeQuotedPrintable: function(str) {
-    return unescape(str.replace(/%/g, "=25").replace(new RegExp('=', 'g'), '%'));
+  decodeQuotedPrintable(str) {
+    return unescape(
+      str.replace(/%/g, "=25").replace(new RegExp("=", "g"), "%")
+    );
   },
 
-  decodeBase64: function(str) {
+  decodeBase64(str) {
     return atob(str.replace(/[\s\r\n]*/g, ""));
   },
 
   /***
    * Encode a string in base64, with a max. line length of 72 characters
    */
-  encodeBase64: function(str) {
+  encodeBase64(str) {
     return btoa(str).replace(/(.{72})/g, "$1\r\n");
   },
 
-  convertToUnicode: function(text, charset) {
-    if (!text || (charset && (charset.toLowerCase() == "iso-8859-1"))) {
+  convertToUnicode(text, charset) {
+    if (!text || (charset && charset.toLowerCase() == "iso-8859-1")) {
       return text;
     }
 
     // Encode plaintext
     try {
       return converter(charset).ConvertToUnicode(text);
-    }
-    catch (ex) {
+    } catch (ex) {
       return text;
     }
   },
 
-  convertFromUnicode: function(text, charset) {
+  convertFromUnicode(text, charset) {
     if (!text) {
       return "";
     }
 
     try {
       return converter(charset).ConvertFromUnicode(text);
-    }
-    catch (ex) {
+    } catch (ex) {
       return text;
     }
   },
 
-  convertGpgToUnicode: function(text) {
-    if (typeof(text) === "string") {
-      text = text.replace(/\\x3a/ig, "\\e3A");
+  convertGpgToUnicode(text) {
+    if (typeof text === "string") {
+      text = text.replace(/\\x3a/gi, "\\e3A");
       var a = text.search(/\\x[0-9a-fA-F]{2}/);
       while (a >= 0) {
-        var ch = unescape('%' + text.substr(a + 2, 2));
+        var ch = unescape("%" + text.substr(a + 2, 2));
         var r = new RegExp("\\" + text.substr(a, 4));
         text = text.replace(r, ch);
 
         a = text.search(/\\x[0-9a-fA-F]{2}/);
       }
 
-      text = EnigmailData.convertToUnicode(text, "utf-8").replace(/\\e3A/g, ":");
+      text = EnigmailData.convertToUnicode(text, "utf-8").replace(
+        /\\e3A/g,
+        ":"
+      );
     }
 
     return text;
   },
 
-  pack: function(value, bytes) {
-    let str = '';
+  pack(value, bytes) {
+    let str = "";
     let mask = 0xff;
     for (let j = 0; j < bytes; j++) {
-      str = String.fromCharCode((value & mask) >> j * 8) + str;
+      str = String.fromCharCode((value & mask) >> (j * 8)) + str;
       mask <<= 8;
     }
 
     return str;
   },
 
-  unpack: function(str) {
+  unpack(str) {
     let len = str.length;
     let value = 0;
 
     for (let j = 0; j < len; j++) {
       value <<= 8;
       value |= str.charCodeAt(j);
     }
 
     return value;
   },
 
-  bytesToHex: function(str) {
+  bytesToHex(str) {
     let len = str.length;
 
-    let hex = '';
+    let hex = "";
     for (let j = 0; j < len; j++) {
       let charCode = str.charCodeAt(j);
-      hex += HEX_TABLE.charAt((charCode & 0xf0) >> 4) +
-        HEX_TABLE.charAt((charCode & 0x0f));
+      hex +=
+        HEX_TABLE.charAt((charCode & 0xf0) >> 4) +
+        HEX_TABLE.charAt(charCode & 0x0f);
     }
 
     return hex;
   },
 
   /**
    * Convert an ArrayBuffer (or Uint8Array) object into a string
    */
-  arrayBufferToString: function(buffer) {
+  arrayBufferToString(buffer) {
     const MAXLEN = 102400;
 
     let uArr = new Uint8Array(buffer);
     let ret = "";
     let len = buffer.byteLength;
 
     for (let j = 0; j < Math.floor(len / MAXLEN) + 1; j++) {
-      ret += String.fromCharCode.apply(null, uArr.subarray(j * MAXLEN, ((j + 1) * MAXLEN)));
+      ret += String.fromCharCode.apply(
+        null,
+        uArr.subarray(j * MAXLEN, (j + 1) * MAXLEN)
+      );
     }
 
     return ret;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/decryption.jsm
+++ b/mail/extensions/openpgp/content/modules/decryption.jsm
@@ -1,78 +1,119 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
+/* eslint-disable complexity */
+
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailDecryption"];
 
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailHttpProxy = ChromeUtils.import("chrome://openpgp/content/modules/httpProxy.jsm").EnigmailHttpProxy;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailErrorHandling = ChromeUtils.import("chrome://openpgp/content/modules/errorHandling.jsm").EnigmailErrorHandling;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailArmor = ChromeUtils.import(
+  "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailHttpProxy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/httpProxy.jsm"
+).EnigmailHttpProxy;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailKey = ChromeUtils.import(
+  "chrome://openpgp/content/modules/key.jsm"
+).EnigmailKey;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
-const STATUS_ERROR = EnigmailConstants.BAD_SIGNATURE | EnigmailConstants.DECRYPTION_FAILED;
-const STATUS_DECRYPTION_OK = EnigmailConstants.DECRYPTION_OKAY;
-const STATUS_GOODSIG = EnigmailConstants.GOOD_SIGNATURE;
-
-const NS_WRONLY = 0x02;
-
-function statusObjectFrom(signatureObj, exitCodeObj, statusFlagsObj, keyIdObj, userIdObj, sigDetailsObj, errorMsgObj, blockSeparationObj, encToDetailsObj) {
+function statusObjectFrom(
+  signatureObj,
+  exitCodeObj,
+  statusFlagsObj,
+  keyIdObj,
+  userIdObj,
+  sigDetailsObj,
+  errorMsgObj,
+  blockSeparationObj,
+  encToDetailsObj
+) {
   return {
     signature: signatureObj,
     exitCode: exitCodeObj,
     statusFlags: statusFlagsObj,
     keyId: keyIdObj,
     userId: userIdObj,
     sigDetails: sigDetailsObj,
     message: errorMsgObj,
     blockSeparation: blockSeparationObj,
-    encToDetails: encToDetailsObj
+    encToDetails: encToDetailsObj,
   };
 }
 
 function newStatusObject() {
-  return statusObjectFrom({
-    value: ""
-  }, {}, {}, {}, {}, {}, {}, {}, {});
+  return statusObjectFrom(
+    {
+      value: "",
+    },
+    {},
+    {},
+    {},
+    {},
+    {},
+    {},
+    {},
+    {}
+  );
 }
 
 var EnigmailDecryption = {
-  isReady: function(win) {
+  isReady(win) {
     // this used to return false while generating a key. still necessary?
     return EnigmailCore.getService(win);
   },
 
-  getFromAddr: function(win) {
+  getFromAddr(win) {
     var fromAddr;
     if (win && win.gFolderDisplay && win.gFolderDisplay.selectedMessage) {
       fromAddr = win.gFolderDisplay.selectedMessage.author;
       try {
         fromAddr = EnigmailFuncs.stripEmail(fromAddr);
         if (fromAddr.search(/[a-zA-Z0-9]@.*[\(\)]/) >= 0) {
           fromAddr = false;
         }
-      }
-      catch (ex) {
+      } catch (ex) {
         fromAddr = false;
       }
     }
     return fromAddr;
   },
 
   /**
    *  Decrypts a PGP ciphertext and returns the the plaintext
@@ -88,332 +129,457 @@ var EnigmailDecryption = {
    *out @sigDetailsObj
    *out @errorMsgObj  error string
    *out @blockSeparationObj
    *out @encToDetailsObj  returns in details, which keys the mesage was encrypted for (ENC_TO entries)
    *
    * @return string plaintext ("" if error)
    *
    */
-  decryptMessage: function(parent, uiFlags, cipherText,
-    signatureObj, exitCodeObj,
-    statusFlagsObj, keyIdObj, userIdObj, sigDetailsObj, errorMsgObj,
-    blockSeparationObj, encToDetailsObj) {
-    const esvc = EnigmailCore.getEnigmailService();
+  decryptMessage(
+    parent,
+    uiFlags,
+    cipherText,
+    signatureObj,
+    exitCodeObj,
+    statusFlagsObj,
+    keyIdObj,
+    userIdObj,
+    sigDetailsObj,
+    errorMsgObj,
+    blockSeparationObj,
+    encToDetailsObj
+  ) {
+    EnigmailLog.DEBUG(
+      "decryption.jsm: decryptMessage(" +
+        cipherText.length +
+        " bytes, " +
+        uiFlags +
+        ")\n"
+    );
 
-    EnigmailLog.DEBUG("decryption.jsm: decryptMessage(" + cipherText.length + " bytes, " + uiFlags + ")\n");
-
-    if (!cipherText)
+    if (!cipherText) {
       return "";
+    }
 
     var interactive = uiFlags & EnigmailConstants.UI_INTERACTIVE;
     var allowImport = uiFlags & EnigmailConstants.UI_ALLOW_KEY_IMPORT;
-    var unverifiedEncryptedOK = uiFlags & EnigmailConstants.UI_UNVERIFIED_ENC_OK;
+    var unverifiedEncryptedOK =
+      uiFlags & EnigmailConstants.UI_UNVERIFIED_ENC_OK;
     var oldSignature = signatureObj.value;
 
-    EnigmailLog.DEBUG("decryption.jsm: decryptMessage: oldSignature=" + oldSignature + "\n");
+    EnigmailLog.DEBUG(
+      "decryption.jsm: decryptMessage: oldSignature=" + oldSignature + "\n"
+    );
 
     signatureObj.value = "";
     exitCodeObj.value = -1;
     statusFlagsObj.value = 0;
     keyIdObj.value = "";
     userIdObj.value = "";
     errorMsgObj.value = "";
 
     var beginIndexObj = {};
     var endIndexObj = {};
     var indentStrObj = {};
-    var blockType = EnigmailArmor.locateArmoredBlock(cipherText, 0, "", beginIndexObj, endIndexObj, indentStrObj);
+    var blockType = EnigmailArmor.locateArmoredBlock(
+      cipherText,
+      0,
+      "",
+      beginIndexObj,
+      endIndexObj,
+      indentStrObj
+    );
     if (!blockType || blockType == "SIGNATURE") {
       // return without displaying a message
       return "";
     }
 
-    var publicKey = (blockType == "PUBLIC KEY BLOCK");
+    var publicKey = blockType == "PUBLIC KEY BLOCK";
+
+    var verifyOnly = blockType == "SIGNED MESSAGE";
 
-    var verifyOnly = (blockType == "SIGNED MESSAGE");
-
-    var pgpBlock = cipherText.substr(beginIndexObj.value,
-      endIndexObj.value - beginIndexObj.value + 1);
+    var pgpBlock = cipherText.substr(
+      beginIndexObj.value,
+      endIndexObj.value - beginIndexObj.value + 1
+    );
 
     if (indentStrObj.value) {
       var indentRegexp = new RegExp("^" + indentStrObj.value, "gm");
       pgpBlock = pgpBlock.replace(indentRegexp, "");
       if (indentStrObj.value.substr(-1) == " ") {
         var indentRegexpStr = "^" + indentStrObj.value.replace(/ $/m, "$");
         indentRegexp = new RegExp(indentRegexpStr, "gm");
         pgpBlock = pgpBlock.replace(indentRegexp, "");
       }
     }
 
     // HACK to better support messages from Outlook: if there are empty lines, drop them
     if (pgpBlock.search(/MESSAGE-----\r?\n\r?\nVersion/) >= 0) {
-      EnigmailLog.DEBUG("decryption.jsm: decryptMessage: apply Outlook empty line workaround\n");
+      EnigmailLog.DEBUG(
+        "decryption.jsm: decryptMessage: apply Outlook empty line workaround\n"
+      );
       pgpBlock = pgpBlock.replace(/\r?\n\r?\n/g, "\n");
     }
 
-    const head = "";
-    var tail = cipherText.substr(endIndexObj.value + 1,
-      cipherText.length - endIndexObj.value - 1);
+    var tail = cipherText.substr(
+      endIndexObj.value + 1,
+      cipherText.length - endIndexObj.value - 1
+    );
 
     if (publicKey) {
       if (!allowImport) {
         errorMsgObj.value = EnigmailLocale.getString("keyInMessageBody");
         statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
         statusFlagsObj.value |= EnigmailConstants.INLINE_KEY;
 
         return "";
       }
 
       // Import public key
-      exitCodeObj.value = EnigmailKeyRing.importKey(parent, true, pgpBlock, "",
-        errorMsgObj);
+      exitCodeObj.value = EnigmailKeyRing.importKey(
+        parent,
+        true,
+        pgpBlock,
+        "",
+        errorMsgObj
+      );
       if (exitCodeObj.value === 0) {
         statusFlagsObj.value |= EnigmailConstants.IMPORTED_KEY;
       }
       return "";
     }
 
     var newSignature = "";
 
     if (verifyOnly) {
-      newSignature = EnigmailArmor.extractSignaturePart(pgpBlock, EnigmailConstants.SIGNATURE_ARMOR);
-      if (oldSignature && (newSignature != oldSignature)) {
-        EnigmailLog.ERROR("enigmail.js: Enigmail.decryptMessage: Error - signature mismatch " + newSignature + "\n");
+      newSignature = EnigmailArmor.extractSignaturePart(
+        pgpBlock,
+        EnigmailConstants.SIGNATURE_ARMOR
+      );
+      if (oldSignature && newSignature != oldSignature) {
+        EnigmailLog.ERROR(
+          "enigmail.js: Enigmail.decryptMessage: Error - signature mismatch " +
+            newSignature +
+            "\n"
+        );
         errorMsgObj.value = EnigmailLocale.getString("sigMismatch");
         statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
 
         return "";
       }
     }
 
     if (!EnigmailCore.getService(parent)) {
-      EnigmailLog.ERROR("decryption.jsm: decryptMessage: not yet initialized\n");
+      EnigmailLog.ERROR(
+        "decryption.jsm: decryptMessage: not yet initialized\n"
+      );
       errorMsgObj.value = EnigmailLocale.getString("notInit");
       statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
       return "";
     }
 
     if (EnigmailKeyRing.isGeneratingKey()) {
       errorMsgObj.value = EnigmailLocale.getString("notComplete");
       statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
       return "";
     }
 
     // limit output to 100 times message size to avoid DoS attack
     var maxOutput = pgpBlock.length * 100;
     let keyserver = EnigmailPrefs.getPref("autoKeyRetrieve");
     let options = {
-      keyserver: keyserver,
+      keyserver,
       keyserverProxy: EnigmailHttpProxy.getHttpProxy(keyserver),
       fromAddr: EnigmailDecryption.getFromAddr(parent),
-      verifyOnly: verifyOnly,
+      verifyOnly,
       noOutput: false,
       maxOutputLength: maxOutput,
-      uiFlags: uiFlags
+      uiFlags,
     };
     const cApi = EnigmailCryptoAPI();
     let result = cApi.sync(cApi.decrypt(pgpBlock, options));
     EnigmailLog.DEBUG("decryption.jsm: decryptMessage: decryption finished\n");
-    if (! result) {
+    if (!result) {
       return "";
     }
 
     var plainText = EnigmailData.getUnicodeData(result.decryptedData);
     exitCodeObj.value = result.exitCode;
     statusFlagsObj.value = result.statusFlags;
     errorMsgObj.value = result.errorMsg;
 
     // do not return anything if gpg signales DECRYPTION_FAILED
     // (which could be possible in case of MDC errors)
-    if ((uiFlags & EnigmailConstants.UI_IGNORE_MDC_ERROR) &&
-      (result.statusFlags & EnigmailConstants.MISSING_MDC)) {
+    if (
+      uiFlags & EnigmailConstants.UI_IGNORE_MDC_ERROR &&
+      result.statusFlags & EnigmailConstants.MISSING_MDC
+    ) {
       EnigmailLog.DEBUG("decryption.jsm: decryptMessage: ignoring MDC error\n");
-    }
-    else if (result.statusFlags & EnigmailConstants.DECRYPTION_FAILED) {
+    } else if (result.statusFlags & EnigmailConstants.DECRYPTION_FAILED) {
       EnigmailLog.DEBUG("decryption.jsm: decryptMessage: failed\n");
       plainText = "";
     }
 
     userIdObj.value = result.userId;
     keyIdObj.value = result.keyId;
     sigDetailsObj.value = result.sigDetails;
     if (encToDetailsObj) {
       encToDetailsObj.value = result.encToDetails;
     }
     blockSeparationObj.value = result.blockSeparation;
 
     if (tail.search(/\S/) >= 0) {
       statusFlagsObj.value |= EnigmailConstants.PARTIALLY_PGP;
     }
 
-
     if (exitCodeObj.value === 0) {
       // Normal return
 
-      var doubleDashSeparator = false;
-      try {
-        doubleDashSeparator = EnigmailPrefs.getPrefBranch().getBoolPref("doubleDashSeparator");
-      }
-      catch (ex) {}
+      let doubleDashSeparator = EnigmailPrefs.getPrefBranch().getBoolPref(
+        "doubleDashSeparator",
+        false
+      );
 
-      if (doubleDashSeparator && (plainText.search(/(\r|\n)-- +(\r|\n)/) < 0)) {
+      if (doubleDashSeparator && plainText.search(/(\r|\n)-- +(\r|\n)/) < 0) {
         // Workaround for MsgCompose stripping trailing spaces from sig separator
         plainText = plainText.replace(/(\r|\n)--(\r|\n)/, "$1-- $2");
       }
 
       statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
 
       if (verifyOnly && indentStrObj.value) {
         plainText = plainText.replace(/^/gm, indentStrObj.value);
       }
 
-      return EnigmailDecryption.inlineInnerVerification(parent, uiFlags, plainText,
-        statusObjectFrom(signatureObj, exitCodeObj, statusFlagsObj, keyIdObj, userIdObj,
-          sigDetailsObj, errorMsgObj, blockSeparationObj, encToDetailsObj));
+      return EnigmailDecryption.inlineInnerVerification(
+        parent,
+        uiFlags,
+        plainText,
+        statusObjectFrom(
+          signatureObj,
+          exitCodeObj,
+          statusFlagsObj,
+          keyIdObj,
+          userIdObj,
+          sigDetailsObj,
+          errorMsgObj,
+          blockSeparationObj,
+          encToDetailsObj
+        )
+      );
     }
 
     var pubKeyId = keyIdObj.value;
 
     if (statusFlagsObj.value & EnigmailConstants.BAD_SIGNATURE) {
       if (verifyOnly && indentStrObj.value) {
         // Probably replied message that could not be verified
-        errorMsgObj.value = EnigmailLocale.getString("unverifiedReply") + "\n\n" + errorMsgObj.value;
+        errorMsgObj.value =
+          EnigmailLocale.getString("unverifiedReply") +
+          "\n\n" +
+          errorMsgObj.value;
         return "";
       }
 
       // Return bad signature (for checking later)
       signatureObj.value = newSignature;
-
-    }
-    else if (pubKeyId &&
-      (statusFlagsObj.value & EnigmailConstants.UNVERIFIED_SIGNATURE)) {
-
+    } else if (
+      pubKeyId &&
+      statusFlagsObj.value & EnigmailConstants.UNVERIFIED_SIGNATURE
+    ) {
       var innerKeyBlock;
       if (verifyOnly) {
         // Search for indented public key block in signed message
-        var innerBlockType = EnigmailArmor.locateArmoredBlock(pgpBlock, 0, "- ", beginIndexObj, endIndexObj, indentStrObj);
+        var innerBlockType = EnigmailArmor.locateArmoredBlock(
+          pgpBlock,
+          0,
+          "- ",
+          beginIndexObj,
+          endIndexObj,
+          indentStrObj
+        );
         if (innerBlockType == "PUBLIC KEY BLOCK") {
-
-          innerKeyBlock = pgpBlock.substr(beginIndexObj.value,
-            endIndexObj.value - beginIndexObj.value + 1);
+          innerKeyBlock = pgpBlock.substr(
+            beginIndexObj.value,
+            endIndexObj.value - beginIndexObj.value + 1
+          );
 
           innerKeyBlock = innerKeyBlock.replace(/- -----/g, "-----");
 
           statusFlagsObj.value |= EnigmailConstants.INLINE_KEY;
-          EnigmailLog.DEBUG("decryption.jsm: decryptMessage: innerKeyBlock found\n");
+          EnigmailLog.DEBUG(
+            "decryption.jsm: decryptMessage: innerKeyBlock found\n"
+          );
         }
       }
 
       if (allowImport) {
-
         var importedKey = false;
 
         if (innerKeyBlock) {
           var importErrorMsgObj = {};
-          var exitStatus = EnigmailKeyRing.importKey(parent, true, innerKeyBlock,
-            pubKeyId, importErrorMsgObj);
+          var exitStatus = EnigmailKeyRing.importKey(
+            parent,
+            true,
+            innerKeyBlock,
+            pubKeyId,
+            importErrorMsgObj
+          );
 
-          importedKey = (exitStatus === 0);
+          importedKey = exitStatus === 0;
 
           if (exitStatus > 0) {
-            EnigmailDialog.alert(parent, EnigmailLocale.getString("cantImport") + importErrorMsgObj.value);
+            EnigmailDialog.alert(
+              parent,
+              EnigmailLocale.getString("cantImport") + importErrorMsgObj.value
+            );
           }
         }
 
         if (importedKey) {
           // Recursive call; note that EnigmailConstants.UI_ALLOW_KEY_IMPORT is unset
           // to break the recursion
           var uiFlagsDeep = interactive ? EnigmailConstants.UI_INTERACTIVE : 0;
           signatureObj.value = "";
-          return EnigmailDecryption.decryptMessage(parent, uiFlagsDeep, pgpBlock,
-            signatureObj, exitCodeObj, statusFlagsObj,
-            keyIdObj, userIdObj, sigDetailsObj, errorMsgObj);
+          return EnigmailDecryption.decryptMessage(
+            parent,
+            uiFlagsDeep,
+            pgpBlock,
+            signatureObj,
+            exitCodeObj,
+            statusFlagsObj,
+            keyIdObj,
+            userIdObj,
+            sigDetailsObj,
+            errorMsgObj
+          );
         }
-
       }
 
       if (plainText && !unverifiedEncryptedOK) {
         // Append original PGP block to unverified message
-        plainText = "-----BEGIN PGP UNVERIFIED MESSAGE-----\r\n" + plainText +
-          "-----END PGP UNVERIFIED MESSAGE-----\r\n\r\n" + pgpBlock;
+        plainText =
+          "-----BEGIN PGP UNVERIFIED MESSAGE-----\r\n" +
+          plainText +
+          "-----END PGP UNVERIFIED MESSAGE-----\r\n\r\n" +
+          pgpBlock;
       }
-
     }
 
     return verifyOnly ? "" : plainText;
   },
 
-  inlineInnerVerification: function(parent, uiFlags, text, statusObject) {
+  inlineInnerVerification(parent, uiFlags, text, statusObject) {
     EnigmailLog.DEBUG("decryption.jsm: inlineInnerVerification()\n");
 
     if (text && text.indexOf("-----BEGIN PGP SIGNED MESSAGE-----") === 0) {
       var status = newStatusObject();
-      var newText = EnigmailDecryption.decryptMessage(parent, uiFlags, text,
-        status.signature, status.exitCode, status.statusFlags, status.keyId, status.userId,
-        status.sigDetails, status.message, status.blockSeparation, status.encToDetails);
+      var newText = EnigmailDecryption.decryptMessage(
+        parent,
+        uiFlags,
+        text,
+        status.signature,
+        status.exitCode,
+        status.statusFlags,
+        status.keyId,
+        status.userId,
+        status.sigDetails,
+        status.message,
+        status.blockSeparation,
+        status.encToDetails
+      );
       if (status.exitCode.value === 0) {
         text = newText;
         // merge status into status object:
-        statusObject.statusFlags.value = statusObject.statusFlags.value | status.statusFlags.value;
+        statusObject.statusFlags.value =
+          statusObject.statusFlags.value | status.statusFlags.value;
         statusObject.keyId.value = status.keyId.value;
         statusObject.userId.value = status.userId.value;
         statusObject.sigDetails.value = status.sigDetails.value;
         statusObject.message.value = status.message.value;
         // we don't merge encToDetails
       }
     }
 
     return text;
   },
 
-  decryptAttachment: function(parent, outFile, displayName, byteData,
-    exitCodeObj, statusFlagsObj, errorMsgObj) {
-    const esvc = EnigmailCore.getEnigmailService();
-
-    EnigmailLog.DEBUG("decryption.jsm: decryptAttachment(parent=" + parent + ", outFileName=" + outFile.path + ")\n");
+  decryptAttachment(
+    parent,
+    outFile,
+    displayName,
+    byteData,
+    exitCodeObj,
+    statusFlagsObj,
+    errorMsgObj
+  ) {
+    EnigmailLog.DEBUG(
+      "decryption.jsm: decryptAttachment(parent=" +
+        parent +
+        ", outFileName=" +
+        outFile.path +
+        ")\n"
+    );
 
     let attachmentHead = byteData.substr(0, 200);
     if (attachmentHead.match(/-----BEGIN PGP \w{5,10} KEY BLOCK-----/)) {
       // attachment appears to be a PGP key file
 
-      if (EnigmailDialog.confirmDlg(parent, EnigmailLocale.getString("attachmentPgpKey", [displayName]),
-          EnigmailLocale.getString("keyMan.button.import"), EnigmailLocale.getString("dlg.button.view"))) {
-
+      if (
+        EnigmailDialog.confirmDlg(
+          parent,
+          EnigmailLocale.getString("attachmentPgpKey", [displayName]),
+          EnigmailLocale.getString("keyMan.button.import"),
+          EnigmailLocale.getString("dlg.button.view")
+        )
+      ) {
         let preview = EnigmailKey.getKeyListFromKeyBlock(byteData, errorMsgObj);
         exitCodeObj.keyList = preview;
         let exitStatus = 0;
 
         if (errorMsgObj.value === "") {
           if (preview.length > 0) {
             if (preview.length == 1) {
-              exitStatus = EnigmailDialog.confirmDlg(parent, EnigmailLocale.getString("doImportOne", [preview[0].name, preview[0].id]));
-            }
-            else {
-              exitStatus = EnigmailDialog.confirmDlg(parent,
+              exitStatus = EnigmailDialog.confirmDlg(
+                parent,
+                EnigmailLocale.getString("doImportOne", [
+                  preview[0].name,
+                  preview[0].id,
+                ])
+              );
+            } else {
+              exitStatus = EnigmailDialog.confirmDlg(
+                parent,
                 EnigmailLocale.getString("doImportMultiple", [
-                  preview.map(function(a) {
-                    return "\t" + a.name + " (" + a.id + ")";
-                  }).
-                  join("\n")
-                ]));
+                  preview
+                    .map(function(a) {
+                      return "\t" + a.name + " (" + a.id + ")";
+                    })
+                    .join("\n"),
+                ])
+              );
             }
 
             if (exitStatus) {
-              exitCodeObj.value = EnigmailKeyRing.importKey(parent, false, byteData, "", errorMsgObj);
+              exitCodeObj.value = EnigmailKeyRing.importKey(
+                parent,
+                false,
+                byteData,
+                "",
+                errorMsgObj
+              );
               statusFlagsObj.value = EnigmailConstants.IMPORTED_KEY;
-            }
-            else {
+            } else {
               exitCodeObj.value = 0;
               statusFlagsObj.value = EnigmailConstants.DISPLAY_MESSAGE;
             }
           }
         }
-      }
-      else {
+      } else {
         exitCodeObj.value = 0;
         statusFlagsObj.value = EnigmailConstants.DISPLAY_MESSAGE;
       }
       return true;
     }
 
     //var outFileName = EnigmailFiles.getEscapedFilename(EnigmailFiles.getFilePathReadonly(outFile.QueryInterface(Ci.nsIFile), NS_WRONLY));
 
@@ -422,10 +588,10 @@ var EnigmailDecryption = {
 
     exitCodeObj.value = result.exitCode;
     statusFlagsObj.value = result.statusFlags;
     if (result.stdoutData.length > 0) {
       return EnigmailFiles.writeFileContents(outFile, result.stdoutData);
     }
 
     return false;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/dialog.jsm
+++ b/mail/extensions/openpgp/content/modules/dialog.jsm
@@ -1,93 +1,108 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailDialog"];
 
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const BUTTON_POS_0 = 1;
-const BUTTON_POS_1 = 1 << 8;
-const BUTTON_POS_2 = 1 << 16;
-
-const gPromptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
 
 const LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";
 
 var EnigmailDialog = {
-
   /***
    * Confirmation dialog with OK / Cancel buttons (both customizable)
    *
    * @win:         nsIWindow - parent window to display modal dialog; can be null
    * @mesg:        String    - message text
    * @okLabel:     String    - OPTIONAL label for OK button
    * @cancelLabel: String    - OPTIONAL label for cancel button
    *
    * @return:      Boolean   - true: OK pressed / false: Cancel or ESC pressed
    */
-  confirmDlg: function(win, mesg, okLabel, cancelLabel) {
-
-    let buttonPressed = EnigmailDialog.msgBox(win, {
+  confirmDlg(win, mesg, okLabel, cancelLabel) {
+    let buttonPressed = EnigmailDialog.msgBox(
+      win,
+      {
         msgtext: mesg,
         button1: okLabel ? okLabel : EnigmailLocale.getString("dlg.button.ok"),
-        cancelButton: cancelLabel ? cancelLabel : EnigmailLocale.getString("dlg.button.cancel"),
+        cancelButton: cancelLabel
+          ? cancelLabel
+          : EnigmailLocale.getString("dlg.button.cancel"),
         iconType: EnigmailConstants.ICONTYPE_QUESTION,
-        dialogTitle: EnigmailLocale.getString("enigConfirm")
+        dialogTitle: EnigmailLocale.getString("enigConfirm"),
       },
-      null);
+      null
+    );
 
-    return (buttonPressed === 0);
+    return buttonPressed === 0;
   },
 
   /**
    * Displays an alert dialog.
    *
    * @win:         nsIWindow - parent window to display modal dialog; can be null
    * @mesg:        String    - message text
    *
    * no return value
    */
-  alert: function(win, mesg) {
-    EnigmailDialog.msgBox(win, {
+  alert(win, mesg) {
+    EnigmailDialog.msgBox(
+      win,
+      {
         msgtext: mesg,
         button1: EnigmailLocale.getString("dlg.button.close"),
         iconType: EnigmailConstants.ICONTYPE_ALERT,
-        dialogTitle: EnigmailLocale.getString("enigAlert")
+        dialogTitle: EnigmailLocale.getString("enigAlert"),
       },
-      null);
+      null
+    );
   },
 
   /**
    * Displays an information dialog.
    *
    * @win:         nsIWindow - parent window to display modal dialog; can be null
    * @mesg:        String    - message text
    *
    * no return value
    */
-  info: function(win, mesg) {
-    EnigmailDialog.msgBox(win, {
+  info(win, mesg) {
+    EnigmailDialog.msgBox(
+      win,
+      {
         msgtext: mesg,
         button1: EnigmailLocale.getString("dlg.button.close"),
         iconType: EnigmailConstants.ICONTYPE_INFO,
-        dialogTitle: EnigmailLocale.getString("enigInfo")
+        dialogTitle: EnigmailLocale.getString("enigInfo"),
       },
-      null);
+      null
+    );
   },
 
   /**
    * Displays an alert dialog with 1-3 optional buttons.
    *
    * @win:           nsIWindow - parent window to display modal dialog; can be null
    * @mesg:          String    - message text
    * @checkboxLabel: String    - if not null, display checkbox with text; the
@@ -96,36 +111,48 @@ var EnigmailDialog = {
    *     use "buttonType:label" or ":buttonType" to indicate special button types
    *        (buttonType is one of cancel, help, extra1, extra2)
    * @checkedObj:    Object    - holding the checkbox value
    *
    * @return: 0-2: button Number pressed
    *          -1: ESC or close window button pressed
    *
    */
-  longAlert: function(win, mesg, checkboxLabel, okLabel, labelButton2, labelButton3, checkedObj) {
+  longAlert(
+    win,
+    mesg,
+    checkboxLabel,
+    okLabel,
+    labelButton2,
+    labelButton3,
+    checkedObj
+  ) {
     var result = {
       value: -1,
-      checked: false
+      checked: false,
     };
 
     if (!win) {
       win = EnigmailWindows.getBestParentWin();
     }
 
-    win.openDialog("chrome://openpgp/content/ui/enigmailMsgBox.xhtml", "_blank",
-      "chrome,dialog,modal,centerscreen,resizable,titlebar", {
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailMsgBox.xhtml",
+      "_blank",
+      "chrome,dialog,modal,centerscreen,resizable,titlebar",
+      {
         msgtext: mesg,
-        checkboxLabel: checkboxLabel,
+        checkboxLabel,
         iconType: EnigmailConstants.ICONTYPE_ALERT,
         button1: okLabel,
         button2: labelButton2,
-        button3: labelButton3
+        button3: labelButton3,
       },
-      result);
+      result
+    );
 
     if (checkboxLabel) {
       checkedObj.value = result.checked;
     }
     return result.value;
   },
 
   /**
@@ -147,76 +174,90 @@ var EnigmailDialog = {
    *     if no button is provided, OK will be displayed
    *
    * @checkedObj:    Object    - holding the checkbox value
    *
    * @return: 0-2: button Number pressed
    *          -1: cancel button, ESC or close window button pressed
    *
    */
-  msgBox: function(win, argsObj, checkedObj) {
+  msgBox(win, argsObj, checkedObj) {
     var result = {
       value: -1,
-      checked: false
+      checked: false,
     };
 
     if (!win) {
       win = EnigmailWindows.getBestParentWin();
     }
 
-    win.openDialog("chrome://openpgp/content/ui/enigmailMsgBox.xhtml", "",
-      "chrome,dialog,modal,centerscreen,resizable", argsObj, result);
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailMsgBox.xhtml",
+      "",
+      "chrome,dialog,modal,centerscreen,resizable",
+      argsObj,
+      result
+    );
 
     if (argsObj.checkboxLabel) {
       checkedObj.value = result.checked;
     }
     return result.value;
   },
 
   /**
    * Display a dialog with a message and a text entry field
    *
    * @win:      nsIWindow - parent window to display modal dialog; can be null
    * @mesg:     String    - message text
    * @valueObj: Object    - object to hold the entered text in .value
    *
    * @return:   Boolean - true if OK was pressed / false otherwise
    */
-  promptValue: function(win, mesg, valueObj) {
-    return gPromptSvc.prompt(win, EnigmailLocale.getString("enigPrompt"),
-      mesg, valueObj, "", {});
+  promptValue(win, mesg, valueObj) {
+    return Services.prompt(
+      win,
+      EnigmailLocale.getString("enigPrompt"),
+      mesg,
+      valueObj,
+      "",
+      {}
+    );
   },
 
   /**
    * Display an alert message with an OK button and a checkbox to hide
    * the message in the future.
    * In case the checkbox was pressed in the past, the dialog is skipped
    *
    * @win:      nsIWindow - the parent window to hold the modal dialog
    * @mesg:     String    - the localized message to display
    * @prefText: String    - the name of the Enigmail preference to read/store the
    *                        the future display status
    */
-  alertPref: function(win, mesg, prefText) {
+  alertPref(win, mesg, prefText) {
     const display = true;
     const dontDisplay = false;
 
     let prefValue = EnigmailPrefs.getPref(prefText);
     if (prefValue === display) {
       let checkBoxObj = {
-        value: false
+        value: false,
       };
 
-      let buttonPressed = EnigmailDialog.msgBox(win, {
+      let buttonPressed = EnigmailDialog.msgBox(
+        win,
+        {
           msgtext: mesg,
           dialogTitle: EnigmailLocale.getString("enigInfo"),
           iconType: EnigmailConstants.ICONTYPE_INFO,
-          checkboxLabel: EnigmailLocale.getString("dlgNoPrompt")
+          checkboxLabel: EnigmailLocale.getString("dlgNoPrompt"),
         },
-        checkBoxObj);
+        checkBoxObj
+      );
 
       if (checkBoxObj.value && buttonPressed === 0) {
         EnigmailPrefs.setPref(prefText, dontDisplay);
       }
     }
   },
 
   /**
@@ -225,30 +266,33 @@ var EnigmailDialog = {
    * If |counter| is 0, the dialog is not displayed.
    *
    * @win:           nsIWindow - the parent window to hold the modal dialog
    * @countPrefName: String    - the name of the Enigmail preference to read/store the
    *                             the |counter| value
    * @mesg:          String    - the localized message to display
    *
    */
-  alertCount: function(win, countPrefName, mesg) {
+  alertCount(win, countPrefName, mesg) {
     let alertCount = EnigmailPrefs.getPref(countPrefName);
 
-    if (alertCount <= 0)
+    if (alertCount <= 0) {
       return;
+    }
 
     alertCount--;
     EnigmailPrefs.setPref(countPrefName, alertCount);
 
     if (alertCount > 0) {
       mesg += EnigmailLocale.getString("repeatPrefix", [alertCount]) + " ";
-      mesg += (alertCount == 1) ? EnigmailLocale.getString("repeatSuffixSingular") : EnigmailLocale.getString("repeatSuffixPlural");
-    }
-    else {
+      mesg +=
+        alertCount == 1
+          ? EnigmailLocale.getString("repeatSuffixSingular")
+          : EnigmailLocale.getString("repeatSuffixPlural");
+    } else {
       mesg += EnigmailLocale.getString("noRepeat");
     }
 
     EnigmailDialog.alert(win, mesg);
   },
 
   /**
    * Display a confirmation dialog with OK / Cancel buttons (both customizable) and
@@ -264,77 +308,90 @@ var EnigmailDialog = {
    * @cancelLabel: String    - OPTIONAL label for cancel button
    *
    * @return:      Boolean   - true: 1 pressed / 0: Cancel pressed / -1: ESC pressed
    *
    * If the dialog is not displayed:
    *  - if @prefText is type Boolean: return 1
    *  - if @prefText is type Number:  return the last choice of the user
    */
-  confirmPref: function(win, mesg, prefText, okLabel, cancelLabel) {
+  confirmPref(win, mesg, prefText, okLabel, cancelLabel) {
     const notSet = 0;
     const yes = 1;
     const no = 2;
     const display = true;
     const dontDisplay = false;
 
     var prefValue = EnigmailPrefs.getPref(prefText);
 
-    if (typeof(prefValue) != "boolean") {
+    if (typeof prefValue != "boolean") {
       // number: remember user's choice
       switch (prefValue) {
-        case notSet:
-          {
-            let checkBoxObj = {
-              value: false
-            };
-            let buttonPressed = EnigmailDialog.msgBox(win, {
+        case notSet: {
+          let checkBoxObj = {
+            value: false,
+          };
+          let buttonPressed = EnigmailDialog.msgBox(
+            win,
+            {
               msgtext: mesg,
-              button1: okLabel ? okLabel : EnigmailLocale.getString("dlg.button.ok"),
-              cancelButton: cancelLabel ? cancelLabel : EnigmailLocale.getString("dlg.button.cancel"),
+              button1: okLabel
+                ? okLabel
+                : EnigmailLocale.getString("dlg.button.ok"),
+              cancelButton: cancelLabel
+                ? cancelLabel
+                : EnigmailLocale.getString("dlg.button.cancel"),
               checkboxLabel: EnigmailLocale.getString("dlgKeepSetting"),
               iconType: EnigmailConstants.ICONTYPE_QUESTION,
-              dialogTitle: EnigmailLocale.getString("enigConfirm")
-            }, checkBoxObj);
+              dialogTitle: EnigmailLocale.getString("enigConfirm"),
+            },
+            checkBoxObj
+          );
 
-            if (checkBoxObj.value) {
-              EnigmailPrefs.setPref(prefText, (buttonPressed === 0 ? yes : no));
-            }
-            return (buttonPressed === 0 ? 1 : 0);
+          if (checkBoxObj.value) {
+            EnigmailPrefs.setPref(prefText, buttonPressed === 0 ? yes : no);
           }
+          return buttonPressed === 0 ? 1 : 0;
+        }
         case yes:
           return 1;
         case no:
           return 0;
         default:
           return -1;
       }
-    }
-    else {
+    } else {
       // boolean: "do not show this dialog anymore" (and return default)
       switch (prefValue) {
-        case display:
-          {
-            let checkBoxObj = {
-              value: false
-            };
-            let buttonPressed = EnigmailDialog.msgBox(win, {
+        case display: {
+          let checkBoxObj = {
+            value: false,
+          };
+          let buttonPressed = EnigmailDialog.msgBox(
+            win,
+            {
               msgtext: mesg,
-              button1: okLabel ? okLabel : EnigmailLocale.getString("dlg.button.ok"),
-              cancelButton: cancelLabel ? cancelLabel : EnigmailLocale.getString("dlg.button.cancel"),
+              button1: okLabel
+                ? okLabel
+                : EnigmailLocale.getString("dlg.button.ok"),
+              cancelButton: cancelLabel
+                ? cancelLabel
+                : EnigmailLocale.getString("dlg.button.cancel"),
               checkboxLabel: EnigmailLocale.getString("dlgNoPrompt"),
               iconType: EnigmailConstants.ICONTYPE_QUESTION,
-              dialogTitle: EnigmailLocale.getString("enigConfirm")
-            }, checkBoxObj);
+              dialogTitle: EnigmailLocale.getString("enigConfirm"),
+            },
+            checkBoxObj
+          );
 
-            if (checkBoxObj.value) {
-              EnigmailPrefs.setPref(prefText, false);
-            }
-            return (buttonPressed === 0 ? 1 : 0);
+          if (checkBoxObj.value) {
+            EnigmailPrefs.setPref(prefText, false);
           }
+          return buttonPressed === 0 ? 1 : 0;
+        }
         case dontDisplay:
           return 1;
         default:
           return -1;
       }
     }
   },
 
@@ -347,59 +404,74 @@ var EnigmailDialog = {
    *  save:             Boolean   - true = Save file / false = Open file
    *  defaultExtension: String    - optional: extension for the type of files to work with, e.g. "asc"
    *  defaultName:      String    - optional: filename, incl. extension, that should be suggested to
    *                                the user as default, e.g. "keys.asc"
    *  filterPairs:      Array     - optional: [title, extension], e.g. ["Pictures", "*.jpg; *.png"]
    *
    *  return value:     nsIFile object representing the file to load or save
    */
-  filePicker: function(win, title, displayDir, save, defaultExtension, defaultName, filterPairs) {
+  filePicker(
+    win,
+    title,
+    displayDir,
+    save,
+    defaultExtension,
+    defaultName,
+    filterPairs
+  ) {
     EnigmailLog.DEBUG("enigmailCommon.jsm: filePicker: " + save + "\n");
 
     let filePicker = Cc["@mozilla.org/filepicker;1"].createInstance();
     filePicker = filePicker.QueryInterface(Ci.nsIFilePicker);
 
     let mode = save ? Ci.nsIFilePicker.modeSave : Ci.nsIFilePicker.modeOpen;
 
     filePicker.init(win, title, mode);
 
     if (displayDir) {
       var localFile = Cc[LOCAL_FILE_CONTRACTID].createInstance(Ci.nsIFile);
 
       try {
         localFile.initWithPath(displayDir);
         filePicker.displayDirectory = localFile;
-      }
-      catch (ex) {}
+      } catch (ex) {}
     }
 
     if (defaultExtension) {
       filePicker.defaultExtension = defaultExtension;
     }
 
     if (defaultName) {
       filePicker.defaultString = defaultName;
     }
 
     let nfilters = 0;
     if (filterPairs && filterPairs.length) {
       nfilters = filterPairs.length / 2;
     }
 
     for (let index = 0; index < nfilters; index++) {
-      filePicker.appendFilter(filterPairs[2 * index], filterPairs[2 * index + 1]);
+      filePicker.appendFilter(
+        filterPairs[2 * index],
+        filterPairs[2 * index + 1]
+      );
     }
 
     filePicker.appendFilters(Ci.nsIFilePicker.filterAll);
 
-    let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+    let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+      Ci.nsIJSInspector
+    );
     let gotFile = null;
     filePicker.open(res => {
-      if (res != Ci.nsIFilePicker.returnOK && res != Ci.nsIFilePicker.returnReplace) {
+      if (
+        res != Ci.nsIFilePicker.returnOK &&
+        res != Ci.nsIFilePicker.returnReplace
+      ) {
         inspector.exitNestedEventLoop();
         return;
       }
 
       gotFile = filePicker.file.QueryInterface(Ci.nsIFile);
       inspector.exitNestedEventLoop();
     });
 
@@ -414,35 +486,39 @@ var EnigmailDialog = {
    *
    * @param win:           nsIWindow - parent window to display modal dialog; can be null
    * @param keyList:       Array of String - imported keyIDs
    *
    * @return: 0-2: button Number pressed
    *          -1: ESC or close window button pressed
    *
    */
-  keyImportDlg: function(win, keyList) {
+  keyImportDlg(win, keyList) {
     var result = {
       value: -1,
-      checked: false
+      checked: false,
     };
 
     if (!win) {
       win = EnigmailWindows.getBestParentWin();
     }
 
-    win.openDialog("chrome://openpgp/content/ui/enigmailKeyImportInfo.xhtml", "",
-      "chrome,dialog,modal,centerscreen,resizable", {
-        keyList: keyList
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailKeyImportInfo.xhtml",
+      "",
+      "chrome,dialog,modal,centerscreen,resizable",
+      {
+        keyList,
       },
-      result);
+      result
+    );
 
     return result.value;
   },
   /**
    * return a pre-initialized prompt service
    */
-  getPromptSvc: function() {
-    return gPromptSvc;
-  }
+  getPromptSvc() {
+    return Services.prompt;
+  },
 };
 
 EnigmailWindows.alert = EnigmailDialog.alert;
--- a/mail/extensions/openpgp/content/modules/encryption.jsm
+++ b/mail/extensions/openpgp/content/modules/encryption.jsm
@@ -1,204 +1,275 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailEncryption"];
 
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailErrorHandling = ChromeUtils.import("chrome://openpgp/content/modules/errorHandling.jsm").EnigmailErrorHandling;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailApp = ChromeUtils.import(
+  "chrome://openpgp/content/modules/app.jsm"
+).EnigmailApp;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailGpg = ChromeUtils.import(
+  "chrome://openpgp/content/modules/gpg.jsm"
+).EnigmailGpg;
+const EnigmailErrorHandling = ChromeUtils.import(
+  "chrome://openpgp/content/modules/errorHandling.jsm"
+).EnigmailErrorHandling;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
-const gMimeHashAlgorithms = [null, "sha1", "ripemd160", "sha256", "sha384", "sha512", "sha224", "md5"];
+const gMimeHashAlgorithms = [
+  null,
+  "sha1",
+  "ripemd160",
+  "sha256",
+  "sha384",
+  "sha512",
+  "sha224",
+  "md5",
+];
 
 const ENC_TYPE_MSG = 0;
 const ENC_TYPE_ATTACH_BINARY = 1;
 const ENC_TYPE_ATTACH_ASCII = 2;
 
-const GPG_COMMENT_OPT = "Using GnuPG with %s - https://doesnotexist-openpgp-integration.thunderbird/";
-
+const GPG_COMMENT_OPT =
+  "Using GnuPG with %s - https://doesnotexist-openpgp-integration.thunderbird/";
 
 var EnigmailEncryption = {
-  getEncryptCommand: function(fromMailAddr, toMailAddr, bccMailAddr, hashAlgorithm, sendFlags, isAscii, errorMsgObj,
-    logFileObj) {
-    EnigmailLog.DEBUG("encryption.jsm: getEncryptCommand: hashAlgorithm=" + hashAlgorithm + "\n");
+  getEncryptCommand(
+    fromMailAddr,
+    toMailAddr,
+    bccMailAddr,
+    hashAlgorithm,
+    sendFlags,
+    isAscii,
+    errorMsgObj,
+    logFileObj
+  ) {
+    EnigmailLog.DEBUG(
+      "encryption.jsm: getEncryptCommand: hashAlgorithm=" + hashAlgorithm + "\n"
+    );
 
     try {
       fromMailAddr = EnigmailFuncs.stripEmail(fromMailAddr);
       toMailAddr = EnigmailFuncs.stripEmail(toMailAddr);
       bccMailAddr = EnigmailFuncs.stripEmail(bccMailAddr);
-
-    }
-    catch (ex) {
+    } catch (ex) {
       errorMsgObj.value = EnigmailLocale.getString("invalidEmail");
       return null;
     }
 
-    var defaultSend = sendFlags & EnigmailConstants.SEND_DEFAULT;
     var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
     var encryptMsg = sendFlags & EnigmailConstants.SEND_ENCRYPTED;
     var usePgpMime = sendFlags & EnigmailConstants.SEND_PGP_MIME;
 
     var useDefaultComment = false;
     try {
       useDefaultComment = EnigmailPrefs.getPref("useDefaultComment");
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     var hushMailSupport = false;
     try {
       hushMailSupport = EnigmailPrefs.getPref("hushMailSupport");
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
-    var detachedSig = (usePgpMime || (sendFlags & EnigmailConstants.SEND_ATTACHMENT)) && signMsg && !encryptMsg;
+    var detachedSig =
+      (usePgpMime || sendFlags & EnigmailConstants.SEND_ATTACHMENT) &&
+      signMsg &&
+      !encryptMsg;
 
     var toAddrList = toMailAddr.split(/\s*,\s*/);
     var bccAddrList = bccMailAddr.split(/\s*,\s*/);
     var k;
 
     var encryptArgs = EnigmailGpg.getStandardArgs(true);
 
-    if (!useDefaultComment)
-      encryptArgs = encryptArgs.concat(["--comment", GPG_COMMENT_OPT.replace(/%s/, EnigmailApp.getName())]);
+    if (!useDefaultComment) {
+      encryptArgs = encryptArgs.concat([
+        "--comment",
+        GPG_COMMENT_OPT.replace(/%s/, EnigmailApp.getName()),
+      ]);
+    }
 
-    var angledFromMailAddr = ((fromMailAddr.search(/^0x/) === 0) || hushMailSupport) ?
-      fromMailAddr : "<" + fromMailAddr + ">";
+    var angledFromMailAddr =
+      fromMailAddr.search(/^0x/) === 0 || hushMailSupport
+        ? fromMailAddr
+        : "<" + fromMailAddr + ">";
     angledFromMailAddr = angledFromMailAddr.replace(/(["'`])/g, "\\$1");
 
     if (signMsg && hashAlgorithm) {
       encryptArgs = encryptArgs.concat(["--digest-algo", hashAlgorithm]);
     }
 
     if (logFileObj) {
       logFileObj.value = EnigmailErrorHandling.getTempLogFile();
       encryptArgs.push("--log-file");
-      encryptArgs.push(EnigmailFiles.getEscapedFilename(EnigmailFiles.getFilePath(logFileObj.value)));
+      encryptArgs.push(
+        EnigmailFiles.getEscapedFilename(
+          EnigmailFiles.getFilePath(logFileObj.value)
+        )
+      );
     }
 
     if (encryptMsg) {
       switch (isAscii) {
         case ENC_TYPE_MSG:
           encryptArgs.push("-a");
           encryptArgs.push("-t");
           break;
         case ENC_TYPE_ATTACH_ASCII:
           encryptArgs.push("-a");
       }
 
       encryptArgs.push("--encrypt");
 
-      if (signMsg)
+      if (signMsg) {
         encryptArgs.push("--sign");
+      }
 
       if (sendFlags & EnigmailConstants.SEND_ALWAYS_TRUST) {
         encryptArgs.push("--trust-model");
         encryptArgs.push("always");
       }
-      if ((sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF) && fromMailAddr)
+      if (sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF && fromMailAddr) {
         encryptArgs = encryptArgs.concat(["--encrypt-to", angledFromMailAddr]);
+      }
 
       for (k = 0; k < toAddrList.length; k++) {
         toAddrList[k] = toAddrList[k].replace(/'/g, "\\'");
         if (toAddrList[k].length > 0) {
           encryptArgs.push("-r");
           if (toAddrList[k].search(/^GROUP:/) === 0) {
             // groups from gpg.conf file
             encryptArgs.push(toAddrList[k].substr(6));
-          }
-          else {
-            encryptArgs.push((hushMailSupport || (toAddrList[k].search(/^0x/) === 0)) ? toAddrList[k] : "<" + toAddrList[k] + ">");
+          } else {
+            encryptArgs.push(
+              hushMailSupport || toAddrList[k].search(/^0x/) === 0
+                ? toAddrList[k]
+                : "<" + toAddrList[k] + ">"
+            );
           }
         }
       }
 
       for (k = 0; k < bccAddrList.length; k++) {
         bccAddrList[k] = bccAddrList[k].replace(/'/g, "\\'");
         if (bccAddrList[k].length > 0) {
           encryptArgs.push("--hidden-recipient");
-          encryptArgs.push((hushMailSupport || (bccAddrList[k].search(/^0x/) === 0)) ? bccAddrList[k] : "<" + bccAddrList[k] + ">");
+          encryptArgs.push(
+            hushMailSupport || bccAddrList[k].search(/^0x/) === 0
+              ? bccAddrList[k]
+              : "<" + bccAddrList[k] + ">"
+          );
         }
       }
-
-    }
-    else if (detachedSig) {
+    } else if (detachedSig) {
       encryptArgs = encryptArgs.concat(["-s", "-b"]);
 
       switch (isAscii) {
         case ENC_TYPE_MSG:
           encryptArgs = encryptArgs.concat(["-a", "-t"]);
           break;
         case ENC_TYPE_ATTACH_ASCII:
           encryptArgs.push("-a");
       }
-
-    }
-    else if (signMsg) {
+    } else if (signMsg) {
       encryptArgs = encryptArgs.concat(["-t", "--clearsign"]);
     }
 
     if (fromMailAddr) {
       encryptArgs = encryptArgs.concat(["-u", angledFromMailAddr]);
     }
 
     return encryptArgs;
   },
 
-
-  getCryptParams: function(fromMailAddr, toMailAddr, bccMailAddr, hashAlgorithm, sendFlags, isAscii, errorMsgObj,
-    logFileObj) {
-
+  getCryptParams(
+    fromMailAddr,
+    toMailAddr,
+    bccMailAddr,
+    hashAlgorithm,
+    sendFlags,
+    isAscii,
+    errorMsgObj,
+    logFileObj
+  ) {
     let result = {};
     result.sender = "";
     result.sign = false;
     result.signatureHash = "";
     result.sigTypeClear = false;
     result.sigTypeDetached = false;
     result.encrypt = false;
     result.encryptToSender = false;
     result.armor = false;
-      
-    EnigmailLog.DEBUG("encryption.jsm: getCryptParams: hashAlgorithm=" + hashAlgorithm + "\n");
+
+    EnigmailLog.DEBUG(
+      "encryption.jsm: getCryptParams: hashAlgorithm=" + hashAlgorithm + "\n"
+    );
 
-    console.debug(`getCryptParams parameters: from=${fromMailAddr}, to=${toMailAddr}, bcc=${bccMailAddr}, hash=${hashAlgorithm}, flags=${sendFlags}, ascii=${isAscii}, errorObj=%o, logObj=%o`,
-                  errorMsgObj, logFileObj);
+    console.debug(
+      `getCryptParams parameters: from=${fromMailAddr}, to=${toMailAddr}, bcc=${bccMailAddr}, hash=${hashAlgorithm}, flags=${sendFlags}, ascii=${isAscii}, errorObj=%o, logObj=%o`,
+      errorMsgObj,
+      logFileObj
+    );
 
     try {
       fromMailAddr = EnigmailFuncs.stripEmail(fromMailAddr);
       toMailAddr = EnigmailFuncs.stripEmail(toMailAddr);
       bccMailAddr = EnigmailFuncs.stripEmail(bccMailAddr);
-    }
-    catch (ex) {
+    } catch (ex) {
       errorMsgObj.value = EnigmailLocale.getString("invalidEmail");
       return null;
     }
 
-    var defaultSend = sendFlags & EnigmailConstants.SEND_DEFAULT;
     var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
     var encryptMsg = sendFlags & EnigmailConstants.SEND_ENCRYPTED;
     var usePgpMime = sendFlags & EnigmailConstants.SEND_PGP_MIME;
 
-    var detachedSig = (usePgpMime || (sendFlags & EnigmailConstants.SEND_ATTACHMENT)) && signMsg && !encryptMsg;
+    var detachedSig =
+      (usePgpMime || sendFlags & EnigmailConstants.SEND_ATTACHMENT) &&
+      signMsg &&
+      !encryptMsg;
 
     result.to = toMailAddr.split(/\s*,\s*/);
     result.bcc = bccMailAddr.split(/\s*,\s*/);
 
     if (result.to.length == 1 && result.to[0].length == 0) {
       result.to.splice(0, 1); // remove the single empty entry
     }
 
@@ -224,17 +295,17 @@ var EnigmailEncryption = {
         result.armor = true;
       }
       result.encrypt = true;
 
       if (signMsg) {
         result.sign = true;
       }
 
-      if ((sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF) && fromMailAddr) {
+      if (sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF && fromMailAddr) {
         result.encryptToSender = true;
       }
 
       var k;
       for (k = 0; k < result.to.length; k++) {
         //result.to[k] = result.to[k].replace(/'/g, "\\'");
         if (result.to[k].length > 0 && result.to[k].search(/^0x/) !== 0) {
           result.to[k] = "<" + result.to[k] + ">";
@@ -242,148 +313,198 @@ var EnigmailEncryption = {
       }
 
       for (k = 0; k < result.bcc.length; k++) {
         //result.bcc[k] = result.bcc[k].replace(/'/g, "\\'");
         if (result.bcc[k].length > 0 && result.bcc[k].search(/^0x/) !== 0) {
           result.bcc[k] = "<" + result.bcc[k] + ">";
         }
       }
-
-    }
-    else if (detachedSig) {
+    } else if (detachedSig) {
       result.sigTypeDetached = true;
 
       if (isAscii != ENC_TYPE_ATTACH_BINARY) {
         result.armor = true;
       }
-    }
-    else if (signMsg) {
+    } else if (signMsg) {
       result.sigTypeClear = true;
     }
 
     console.debug(`getCryptParams returning:`);
     console.debug(result);
     return result;
   },
 
-
   /**
    * Determine if the sender key ID or user ID can be used for signing and/or encryption
    *
    * @param sendFlags:    Number  - the send Flags; need to contain SEND_SIGNED and/or SEND_ENCRYPTED
    * @param fromMailAddr: String  - the sender email address or key ID
    *
    * @return Object:
    *         - keyId:    String - the found key ID, or null if fromMailAddr is not valid
    *         - errorMsg: String - the erorr message if key not valid, or null if key is valid
    */
-  determineOwnKeyUsability: function(sendFlags, fromMailAddr) {
-    EnigmailLog.DEBUG("encryption.jsm: determineOwnKeyUsability: sendFlags=" + sendFlags + ", sender=" + fromMailAddr + "\n");
+  determineOwnKeyUsability(sendFlags, fromMailAddr) {
+    EnigmailLog.DEBUG(
+      "encryption.jsm: determineOwnKeyUsability: sendFlags=" +
+        sendFlags +
+        ", sender=" +
+        fromMailAddr +
+        "\n"
+    );
 
     let keyList = [];
     let ret = {
       keyId: null,
-      errorMsg: null
+      errorMsg: null,
     };
 
-    let sign = (sendFlags & EnigmailConstants.SEND_SIGNED ? true : false);
-    let encrypt = (sendFlags & EnigmailConstants.SEND_ENCRYPTED ? true : false);
+    let sign = !!(sendFlags & EnigmailConstants.SEND_SIGNED);
+    let encrypt = !!(sendFlags & EnigmailConstants.SEND_ENCRYPTED);
 
     if (fromMailAddr.search(/^(0x)?[A-Z0-9]+$/) === 0) {
       // key ID specified
       let key = EnigmailKeyRing.getKeyById(fromMailAddr);
       keyList.push(key);
-    }
-    else {
+    } else {
       // email address specified
       keyList = EnigmailKeyRing.getKeysByUserId(fromMailAddr);
     }
 
     if (keyList.length === 0) {
-      ret.errorMsg = EnigmailLocale.getString("errorOwnKeyUnusable", fromMailAddr);
+      ret.errorMsg = EnigmailLocale.getString(
+        "errorOwnKeyUnusable",
+        fromMailAddr
+      );
       return ret;
     }
 
     if (sign) {
-      keyList = keyList.reduce(function _f(p, keyObj) {
-        if (keyObj && keyObj.getSigningValidity().keyValid) p.push(keyObj);
+      keyList = keyList.reduce(function(p, keyObj) {
+        if (keyObj && keyObj.getSigningValidity().keyValid) {
+          p.push(keyObj);
+        }
         return p;
       }, []);
     }
 
     if (encrypt) {
-      keyList = keyList.reduce(function _f(p, keyObj) {
-        if (keyObj && keyObj.getEncryptionValidity().keyValid) p.push(keyObj);
+      keyList = keyList.reduce(function(p, keyObj) {
+        if (keyObj && keyObj.getEncryptionValidity().keyValid) {
+          p.push(keyObj);
+        }
         return p;
       }, []);
     }
 
     if (keyList.length === 0) {
       if (sign) {
-        ret.errorMsg = EnigmailErrorHandling.determineInvSignReason(fromMailAddr);
+        ret.errorMsg = EnigmailErrorHandling.determineInvSignReason(
+          fromMailAddr
+        );
+      } else {
+        ret.errorMsg = EnigmailErrorHandling.determineInvRcptReason(
+          fromMailAddr
+        );
       }
-      else {
-        ret.errorMsg = EnigmailErrorHandling.determineInvRcptReason(fromMailAddr);
-      }
-    }
-    else {
+    } else {
       ret.keyId = keyList[0].fpr;
     }
 
     return ret;
   },
 
-  encryptMessageStart: function(win, uiFlags, fromMailAddr, toMailAddr, bccMailAddr,
-    hashAlgorithm, sendFlags, listener, statusFlagsObj, errorMsgObj) {
-    EnigmailLog.DEBUG("encryption.jsm: encryptMessageStart: uiFlags=" + uiFlags + ", from " + fromMailAddr + " to " + toMailAddr + ", hashAlgorithm=" + hashAlgorithm + " (" + EnigmailData.bytesToHex(
-      EnigmailData.pack(sendFlags, 4)) + ")\n");
+  encryptMessageStart(
+    win,
+    uiFlags,
+    fromMailAddr,
+    toMailAddr,
+    bccMailAddr,
+    hashAlgorithm,
+    sendFlags,
+    listener,
+    statusFlagsObj,
+    errorMsgObj
+  ) {
+    EnigmailLog.DEBUG(
+      "encryption.jsm: encryptMessageStart: uiFlags=" +
+        uiFlags +
+        ", from " +
+        fromMailAddr +
+        " to " +
+        toMailAddr +
+        ", hashAlgorithm=" +
+        hashAlgorithm +
+        " (" +
+        EnigmailData.bytesToHex(EnigmailData.pack(sendFlags, 4)) +
+        ")\n"
+    );
 
     let keyUseability = this.determineOwnKeyUsability(sendFlags, fromMailAddr);
 
     if (!keyUseability.keyId) {
-      EnigmailLog.DEBUG("encryption.jsm: encryptMessageStart: own key invalid\n");
+      EnigmailLog.DEBUG(
+        "encryption.jsm: encryptMessageStart: own key invalid\n"
+      );
       errorMsgObj.value = keyUseability.errorMsg;
-      statusFlagsObj.value = EnigmailConstants.INVALID_RECIPIENT | EnigmailConstants.NO_SECKEY | EnigmailConstants.DISPLAY_MESSAGE;
+      statusFlagsObj.value =
+        EnigmailConstants.INVALID_RECIPIENT |
+        EnigmailConstants.NO_SECKEY |
+        EnigmailConstants.DISPLAY_MESSAGE;
 
       return null;
     }
 
     var pgpMime = uiFlags & EnigmailConstants.UI_PGP_MIME;
 
-    var hashAlgo = gMimeHashAlgorithms[EnigmailPrefs.getPref("mimeHashAlgorithm")];
+    var hashAlgo =
+      gMimeHashAlgorithms[EnigmailPrefs.getPref("mimeHashAlgorithm")];
 
     if (hashAlgorithm) {
       hashAlgo = hashAlgorithm;
     }
 
     errorMsgObj.value = "";
 
     if (!sendFlags) {
-      EnigmailLog.DEBUG("encryption.jsm: encryptMessageStart: NO ENCRYPTION!\n");
+      EnigmailLog.DEBUG(
+        "encryption.jsm: encryptMessageStart: NO ENCRYPTION!\n"
+      );
       errorMsgObj.value = EnigmailLocale.getString("notRequired");
       return null;
     }
 
     if (!EnigmailCore.getService(win)) {
-      EnigmailLog.ERROR("encryption.jsm: encryptMessageStart: not yet initialized\n");
+      EnigmailLog.ERROR(
+        "encryption.jsm: encryptMessageStart: not yet initialized\n"
+      );
       errorMsgObj.value = EnigmailLocale.getString("notInit");
       return null;
     }
 
     let logFileObj = {};
 
     // GnuPG
     // let encryptArgs = EnigmailEncryption.getEncryptCommand(fromMailAddr, toMailAddr, bccMailAddr, hashAlgo, sendFlags, ENC_TYPE_MSG, errorMsgObj, logFileObj);
-    let encryptArgs = EnigmailEncryption.getCryptParams(fromMailAddr, toMailAddr, bccMailAddr, hashAlgo, sendFlags, ENC_TYPE_MSG, errorMsgObj, logFileObj);
+    let encryptArgs = EnigmailEncryption.getCryptParams(
+      fromMailAddr,
+      toMailAddr,
+      bccMailAddr,
+      hashAlgo,
+      sendFlags,
+      ENC_TYPE_MSG,
+      errorMsgObj,
+      logFileObj
+    );
 
-    if (!encryptArgs)
+    if (!encryptArgs) {
       return null;
+    }
 
-    var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
     if (!listener) {
       listener = {};
     }
     if ("done" in listener) {
       listener.outerDone = listener.done;
     }
 
     listener.done = function(exitCode) {
@@ -391,106 +512,158 @@ var EnigmailEncryption = {
       if (this.outerDone) {
         this.outerDone(exitCode);
       }
     };
 
     let resultStatus = {};
     const cApi = EnigmailCryptoAPI();
     console.debug("listener: %o", listener);
-    let encrypted = cApi.sync(cApi.encryptAndOrSign(listener.getInputForEncryption(), encryptArgs, resultStatus));
+    let encrypted = cApi.sync(
+      cApi.encryptAndOrSign(
+        listener.getInputForEncryption(),
+        encryptArgs,
+        resultStatus
+      )
+    );
     console.debug(`encryptAndOrSign returned: ${encrypted}`);
 
     listener.addEncryptedOutput(encrypted);
 
     if (pgpMime && errorMsgObj.value) {
       EnigmailDialog.alert(win, errorMsgObj.value);
     }
 
     listener.done(resultStatus.exitCode);
 
     //return proc;
     return null;
   },
 
-  encryptMessageEnd: function(fromMailAddr, stderrStr, exitCode, uiFlags, sendFlags, outputLen, retStatusObj) {
-    EnigmailLog.DEBUG("encryption.jsm: encryptMessageEnd: uiFlags=" + uiFlags + ", sendFlags=" + EnigmailData.bytesToHex(EnigmailData.pack(sendFlags, 4)) + ", outputLen=" + outputLen + "\n");
+  encryptMessageEnd(
+    fromMailAddr,
+    stderrStr,
+    exitCode,
+    uiFlags,
+    sendFlags,
+    outputLen,
+    retStatusObj
+  ) {
+    EnigmailLog.DEBUG(
+      "encryption.jsm: encryptMessageEnd: uiFlags=" +
+        uiFlags +
+        ", sendFlags=" +
+        EnigmailData.bytesToHex(EnigmailData.pack(sendFlags, 4)) +
+        ", outputLen=" +
+        outputLen +
+        "\n"
+    );
 
-    var pgpMime = uiFlags & EnigmailConstants.UI_PGP_MIME;
-    var defaultSend = sendFlags & EnigmailConstants.SEND_DEFAULT;
     var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
     var encryptMsg = sendFlags & EnigmailConstants.SEND_ENCRYPTED;
 
     retStatusObj.statusFlags = 0;
     retStatusObj.errorMsg = "";
     retStatusObj.blockSeparation = "";
 
     if (!EnigmailCore.getService().initialized) {
-      EnigmailLog.ERROR("encryption.jsm: encryptMessageEnd: not yet initialized\n");
+      EnigmailLog.ERROR(
+        "encryption.jsm: encryptMessageEnd: not yet initialized\n"
+      );
       retStatusObj.errorMsg = EnigmailLocale.getString("notInit");
       return -1;
     }
 
     //EnigmailErrorHandling.parseErrorOutput(stderrStr, retStatusObj);
 
     //exitCode = EnigmailExecution.fixExitCode(exitCode, retStatusObj);
-    if ((exitCode === 0) && !outputLen) {
+    if (exitCode === 0 && !outputLen) {
       exitCode = -1;
     }
 
     if (exitCode !== 0 && (signMsg || encryptMsg)) {
       // GnuPG might return a non-zero exit code, even though the message was correctly
       // signed or encryped -> try to fix the exit code
 
       var correctedExitCode = 0;
       if (signMsg) {
-        if (!(retStatusObj.statusFlags & EnigmailConstants.SIG_CREATED)) correctedExitCode = exitCode;
+        if (!(retStatusObj.statusFlags & EnigmailConstants.SIG_CREATED)) {
+          correctedExitCode = exitCode;
+        }
       }
       if (encryptMsg) {
-        if (!(retStatusObj.statusFlags & EnigmailConstants.END_ENCRYPTION)) correctedExitCode = exitCode;
+        if (!(retStatusObj.statusFlags & EnigmailConstants.END_ENCRYPTION)) {
+          correctedExitCode = exitCode;
+        }
       }
       exitCode = correctedExitCode;
     }
 
-    EnigmailLog.DEBUG("encryption.jsm: encryptMessageEnd: command execution exit code: " + exitCode + "\n");
+    EnigmailLog.DEBUG(
+      "encryption.jsm: encryptMessageEnd: command execution exit code: " +
+        exitCode +
+        "\n"
+    );
 
     if (retStatusObj.statusFlags & EnigmailConstants.DISPLAY_MESSAGE) {
       if (retStatusObj.extendedStatus.search(/\bdisp:/) >= 0) {
         retStatusObj.errorMsg = retStatusObj.statusMsg;
-      }
-      else {
+      } else {
         if (fromMailAddr.search(/^0x/) === 0) {
           fromMailAddr = fromMailAddr.substr(2);
         }
         if (fromMailAddr.search(/^[A-F0-9]{8,40}$/i) === 0) {
           fromMailAddr = "[A-F0-9]+" + fromMailAddr;
         }
 
-        let s = new RegExp("^(\\[GNUPG:\\] )?INV_(RECP|SGNR) [0-9]+ (\\<|0x)?" + fromMailAddr + "\\>?", "m");
+        let s = new RegExp(
+          "^(\\[GNUPG:\\] )?INV_(RECP|SGNR) [0-9]+ (\\<|0x)?" +
+            fromMailAddr +
+            "\\>?",
+          "m"
+        );
         if (retStatusObj.statusMsg.search(s) >= 0) {
-          retStatusObj.errorMsg += "\n\n" + EnigmailLocale.getString("keyError.resolutionAction");
-        }
-        else if (retStatusObj.statusMsg.length > 0) {
+          retStatusObj.errorMsg +=
+            "\n\n" + EnigmailLocale.getString("keyError.resolutionAction");
+        } else if (retStatusObj.statusMsg.length > 0) {
           retStatusObj.errorMsg = retStatusObj.statusMsg;
         }
       }
-    }
-    else if (retStatusObj.statusFlags & EnigmailConstants.INVALID_RECIPIENT) {
+    } else if (retStatusObj.statusFlags & EnigmailConstants.INVALID_RECIPIENT) {
       retStatusObj.errorMsg = retStatusObj.statusMsg;
-    }
-    else if (exitCode !== 0) {
+    } else if (exitCode !== 0) {
       retStatusObj.errorMsg = EnigmailLocale.getString("badCommand");
     }
 
     return exitCode;
   },
 
-  encryptMessage: function(parent, uiFlags, plainText, fromMailAddr, toMailAddr, bccMailAddr, sendFlags,
-    exitCodeObj, statusFlagsObj, errorMsgObj) {
-    EnigmailLog.DEBUG("enigmail.js: Enigmail.encryptMessage: " + plainText.length + " bytes from " + fromMailAddr + " to " + toMailAddr + " (" + sendFlags + ")\n");
+  encryptMessage(
+    parent,
+    uiFlags,
+    plainText,
+    fromMailAddr,
+    toMailAddr,
+    bccMailAddr,
+    sendFlags,
+    exitCodeObj,
+    statusFlagsObj,
+    errorMsgObj
+  ) {
+    EnigmailLog.DEBUG(
+      "enigmail.js: Enigmail.encryptMessage: " +
+        plainText.length +
+        " bytes from " +
+        fromMailAddr +
+        " to " +
+        toMailAddr +
+        " (" +
+        sendFlags +
+        ")\n"
+    );
     throw new Error("Not implemented");
 
     /*
     exitCodeObj.value = -1;
     statusFlagsObj.value = 0;
     errorMsgObj.value = "";
 
     if (!plainText) {
--- a/mail/extensions/openpgp/content/modules/errorHandling.jsm
+++ b/mail/extensions/openpgp/content/modules/errorHandling.jsm
@@ -3,584 +3,150 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailErrorHandling"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-
-const getEnigmailKeyRing = EnigmailLazy.loader("enigmail/keyRing.jsm", "EnigmailKeyRing");
-const getEnigmailGpg = EnigmailLazy.loader("enigmail/gpg.jsm", "EnigmailGpg");
-const getEnigmailFiles = EnigmailLazy.loader("enigmail/files.jsm", "EnigmailFiles");
-const getEnigmailRNG = EnigmailLazy.loader("enigmail/rng.jsm", "EnigmailRNG");
-
-
-const gStatusFlags = {
-  GOODSIG: EnigmailConstants.GOOD_SIGNATURE,
-  BADSIG: EnigmailConstants.BAD_SIGNATURE,
-  ERRSIG: EnigmailConstants.UNVERIFIED_SIGNATURE,
-  EXPSIG: EnigmailConstants.EXPIRED_SIGNATURE,
-  REVKEYSIG: EnigmailConstants.GOOD_SIGNATURE,
-  EXPKEYSIG: EnigmailConstants.EXPIRED_KEY_SIGNATURE,
-  KEYEXPIRED: EnigmailConstants.EXPIRED_KEY,
-  KEYREVOKED: EnigmailConstants.REVOKED_KEY,
-  NO_PUBKEY: EnigmailConstants.NO_PUBKEY,
-  NO_SECKEY: EnigmailConstants.NO_SECKEY,
-  IMPORTED: EnigmailConstants.IMPORTED_KEY,
-  INV_RECP: EnigmailConstants.INVALID_RECIPIENT,
-  MISSING_PASSPHRASE: EnigmailConstants.MISSING_PASSPHRASE,
-  BAD_PASSPHRASE: EnigmailConstants.BAD_PASSPHRASE,
-  BADARMOR: EnigmailConstants.BAD_ARMOR,
-  NODATA: EnigmailConstants.NODATA,
-  ERROR: EnigmailConstants.BAD_SIGNATURE | EnigmailConstants.DECRYPTION_FAILED,
-  DECRYPTION_FAILED: EnigmailConstants.DECRYPTION_FAILED,
-  DECRYPTION_OKAY: EnigmailConstants.DECRYPTION_OKAY,
-  CARDCTRL: EnigmailConstants.CARDCTRL,
-  SC_OP_FAILURE: EnigmailConstants.SC_OP_FAILURE,
-  UNKNOWN_ALGO: EnigmailConstants.UNKNOWN_ALGO,
-  SIG_CREATED: EnigmailConstants.SIG_CREATED,
-  END_ENCRYPTION: EnigmailConstants.END_ENCRYPTION,
-  INV_SGNR: 0x100000000,
-  IMPORT_OK: 0x200000000,
-  FAILURE: 0x400000000,
-  DECRYPTION_INFO: 0x800000000
-};
-
-// taken from libgpg-error: gpg-error.h
-const GPG_SOURCE_SYSTEM = {
-  GPG_ERR_SOURCE_UNKNOWN: 0,
-  GPG_ERR_SOURCE_GCRYPT: 1,
-  GPG_ERR_SOURCE_GPG: 2,
-  GPG_ERR_SOURCE_GPGSM: 3,
-  GPG_ERR_SOURCE_GPGAGENT: 4,
-  GPG_ERR_SOURCE_PINENTRY: 5,
-  GPG_ERR_SOURCE_SCD: 6,
-  GPG_ERR_SOURCE_GPGME: 7,
-  GPG_ERR_SOURCE_KEYBOX: 8,
-  GPG_ERR_SOURCE_KSBA: 9,
-  GPG_ERR_SOURCE_DIRMNGR: 10,
-  GPG_ERR_SOURCE_GSTI: 11,
-  GPG_ERR_SOURCE_GPA: 12,
-  GPG_ERR_SOURCE_KLEO: 13,
-  GPG_ERR_SOURCE_G13: 14,
-  GPG_ERR_SOURCE_ASSUAN: 15,
-  GPG_ERR_SOURCE_TLS: 17,
-  GPG_ERR_SOURCE_ANY: 31
-};
-
-/**
- * Handling of specific error codes from GnuPG
- *
- * @param c           Object - the retStatusObj
- * @param errorNumber String - the error number as printed by GnuPG
- */
-function handleErrorCode(c, errorNumber) {
-  if (errorNumber && errorNumber.search(/^[0-9]+$/) === 0) {
-    let errNum = Number(errorNumber);
-    let sourceSystem = errNum >> 24;
-    let errorCode = errNum & 0xFFFFFF;
-
-    switch (errorCode) {
-      case 32870: // error no tty
-        if (sourceSystem === GPG_SOURCE_SYSTEM.GPG_ERR_SOURCE_PINENTRY) {
-          c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-          c.retStatusObj.extendedStatus += "disp:get_passphrase ";
-          c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.pinentryCursesError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
-          c.isError = true;
-        }
-        break;
-      case 11: // bad Passphrase
-      case 87: // bad PIN
-        badPassphrase(c);
-        break;
-      case 177: // no passphrase
-      case 178: // no PIN
-        missingPassphrase(c);
-        break;
-      case 99: // operation canceled
-        if (sourceSystem === GPG_SOURCE_SYSTEM.GPG_ERR_SOURCE_PINENTRY) {
-          missingPassphrase(c);
-        }
-        break;
-      case 77: // no agent
-      case 78: // agent error
-      case 80: // assuan server fault
-      case 81: // assuan error
-        c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-        c.retStatusObj.extendedStatus += "disp:get_passphrase ";
-        c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.gpgAgentError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
-        c.isError = true;
-        break;
-      case 85: // no pinentry
-      case 86: // pinentry error
-        c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-        c.retStatusObj.extendedStatus += "disp:get_passphrase ";
-        c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.pinentryError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
-        c.isError = true;
-        break;
-      case 92: // no dirmngr
-      case 93: // dirmngr error
-        c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-        c.retStatusObj.extendedStatus += "disp:get_passphrase ";
-        c.retStatusObj.statusMsg = "";
-        c.isError = true;
-        break;
-      case 2:
-      case 3:
-      case 149:
-      case 188:
-        c.statusFlags |= EnigmailConstants.UNKNOWN_ALGO;
-        break;
-      case 15:
-        c.statusFlags |= EnigmailConstants.BAD_ARMOR;
-        break;
-      case 58:
-        c.statusFlags |= EnigmailConstants.NODATA;
-        break;
-    }
-  }
-}
-
-/**
- * Special treatment for some ERROR messages from GnuPG
- *
- * extendedStatus are preceeded by "disp:" if an error message is set in statusMsg
- *
- * isError is set to true if this is a hard error that makes further processing of
- * the status codes useless
- */
-function handleError(c) {
-  /*
-    check_hijacking: gpg-agent was hijacked by some other process (like gnome-keyring)
-    proc_pkt.plaintext: multiple plaintexts seen
-    pkdecrypt_failed: public key decryption failed
-    keyedit.passwd: error changing the passphrase
-    card_key_generate: key generation failed (card)
-    key_generate: key generation failed
-    keyserver_send: keyserver send failed
-    get_passphrase: gpg-agent cannot query the passphrase from pinentry (GnuPG 2.0.x)
-  */
-
-  var lineSplit = c.statusLine.split(/ +/);
-  if (lineSplit.length > 0) {
-
-    if (lineSplit.length >= 3) {
-      // first check if the error code is a specifically treated hard failure
-      handleErrorCode(c, lineSplit[2]);
-      if (c.isError) return true;
-    }
-
-    switch (lineSplit[1]) {
-      case "check_hijacking":
-        c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-        c.retStatusObj.extendedStatus += "disp:invalid_gpg_agent ";
-        c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.gpgAgentInvalid") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
-        c.isError = true;
-        break;
-      case "get_passphrase":
-        c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-        c.retStatusObj.extendedStatus += "disp:get_passphrase ";
-        c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.pinentryError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
-        c.isError = true;
-        break;
-      case "proc_pkt.plaintext":
-        c.retStatusObj.extendedStatus += "multiple_plaintexts ";
-        c.isError = true;
-        break;
-      case "pkdecrypt_failed":
-        c.retStatusObj.extendedStatus += "pubkey_decrypt ";
-        handleErrorCode(c, lineSplit[2]);
-        break;
-      case "keyedit.passwd":
-        c.retStatusObj.extendedStatus += "passwd_change_failed ";
-        break;
-      case "card_key_generate":
-      case "key_generate":
-        c.retStatusObj.extendedStatus += "key_generate_failure ";
-        break;
-      case "keyserver_send":
-        c.retStatusObj.extendedStatus += "keyserver_send_failed ";
-        c.isError = true;
-        break;
-      default:
-        return false;
-    }
-    return true;
-  } else {
-    return false;
-  }
-}
-
-// handle GnuPG FAILURE message (GnuPG 2.1.10 and newer)
-function failureMessage(c) {
-  let lineSplit = c.statusLine.split(/ +/);
-  if (lineSplit.length >= 3) {
-    handleErrorCode(c, lineSplit[2]);
-  }
-}
-
-function missingPassphrase(c) {
-  c.statusFlags |= EnigmailConstants.MISSING_PASSPHRASE;
-  if (c.retStatusObj.statusMsg.indexOf(EnigmailLocale.getString("missingPassphrase")) < 0) {
-    c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-    c.flag = 0;
-    EnigmailLog.DEBUG("errorHandling.jsm: missingPassphrase: missing passphrase\n");
-    c.retStatusObj.statusMsg += EnigmailLocale.getString("missingPassphrase") + "\n";
-  }
-}
-
-function badPassphrase(c) {
-  c.statusFlags |= EnigmailConstants.MISSING_PASSPHRASE;
-  if (!(c.statusFlags & EnigmailConstants.BAD_PASSPHRASE)) {
-    c.statusFlags |= EnigmailConstants.BAD_PASSPHRASE;
-    c.flag = 0;
-    EnigmailLog.DEBUG("errorHandling.jsm: badPassphrase: bad passphrase\n");
-    c.retStatusObj.statusMsg += EnigmailLocale.getString("badPhrase") + "\n";
-  }
-}
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
 
-
-function invalidSignature(c) {
-  if (c.isError) return;
-  var lineSplit = c.statusLine.split(/ +/);
-  c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-  c.flag = 0;
-
-  let keySpec = lineSplit[2];
-
-  if (keySpec) {
-    EnigmailLog.DEBUG("errorHandling.jsm: invalidRecipient: detected invalid sender " + keySpec + " / code: " + lineSplit[1] + "\n");
-    c.retStatusObj.errorMsg += EnigmailErrorHandling.determineInvSignReason(keySpec);
-  }
-}
-
-function invalidRecipient(c) {
-  if (c.isError) return;
-  var lineSplit = c.statusLine.split(/ +/);
-  c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
-  c.flag = 0;
-
-  let keySpec = lineSplit[2];
-
-  if (keySpec) {
-    EnigmailLog.DEBUG("errorHandling.jsm: invalidRecipient: detected invalid recipient " + keySpec + " / code: " + lineSplit[1] + "\n");
-    c.retStatusObj.errorMsg += EnigmailErrorHandling.determineInvRcptReason(keySpec);
-  }
-}
-
-function importOk(c) {
-  var lineSplit = c.statusLine.split(/ +/);
-  if (lineSplit.length > 1) {
-    EnigmailLog.DEBUG("errorHandling.jsm: importOk: key imported: " + lineSplit[2] + "\n");
-  } else {
-    EnigmailLog.DEBUG("errorHandling.jsm: importOk: key without FPR imported\n");
-  }
-}
-
-function unverifiedSignature(c) {
-  var lineSplit = c.statusLine.split(/ +/);
-  if (lineSplit.length > 7 && lineSplit[7] == "4") {
-    c.flag = EnigmailConstants.UNKNOWN_ALGO;
-  }
-}
-
-function noData(c) {
-  // Recognize only "NODATA 1"
-  if (c.statusLine.search(/NODATA 1\b/) < 0) {
-    c.flag = 0;
-  }
-}
-
-function decryptionInfo(c) {
-  // Recognize "DECRYPTION_INFO 0 1 2"
-  if (c.statusLine.search(/DECRYPTION_INFO /) >= 0) {
-    let lineSplit = c.statusLine.split(/ +/);
-
-    let mdcMethod = lineSplit[1];
-    let aeadAlgo = lineSplit.length > 3 ? lineSplit[3] : "0";
-
-    if (mdcMethod === "0" && aeadAlgo === "0") {
-      c.statusFlags |= EnigmailConstants.MISSING_MDC;
-      c.statusFlags |= EnigmailConstants.DECRYPTION_FAILED; // be sure to fail
-      c.flag = EnigmailConstants.MISSING_MDC;
-      EnigmailLog.DEBUG("errorHandling.jsm: missing MDC!\n");
-      c.retStatusObj.statusMsg += EnigmailLocale.getString("missingMdcError") + "\n";
-    }
-  }
-}
-
-
-function decryptionFailed(c) {
-  c.inDecryptionFailed = true;
-}
-
-function cardControl(c) {
-  var lineSplit = c.statusLine.split(/ +/);
-  if (lineSplit[1] == "3") {
-    c.detectedCard = lineSplit[2];
-  } else {
-    c.errCode = Number(lineSplit[1]);
-    if (c.errCode == 1) c.requestedCard = lineSplit[2];
-  }
-}
-
-function setupFailureLookup() {
-  var result = {};
-  result[EnigmailConstants.DECRYPTION_FAILED] = decryptionFailed;
-  result[EnigmailConstants.NODATA] = noData;
-  result[EnigmailConstants.CARDCTRL] = cardControl;
-  result[EnigmailConstants.UNVERIFIED_SIGNATURE] = unverifiedSignature;
-  result[EnigmailConstants.MISSING_PASSPHRASE] = missingPassphrase;
-  result[EnigmailConstants.BAD_PASSPHRASE] = badPassphrase;
-  result[gStatusFlags.INV_RECP] = invalidRecipient;
-  result[gStatusFlags.INV_SGNR] = invalidSignature;
-  result[gStatusFlags.IMPORT_OK] = importOk;
-  result[gStatusFlags.FAILURE] = failureMessage;
-  result[gStatusFlags.DECRYPTION_INFO] = decryptionInfo;
-  return result;
-}
-
-function ignore() {}
-
-const failureLookup = setupFailureLookup();
-
-function handleFailure(c, errorFlag) {
-  c.flag = gStatusFlags[errorFlag]; // yields known flag or undefined
-
-  (failureLookup[c.flag] || ignore)(c);
-
-  // if known flag, story it in our status
-  if (c.flag) {
-    c.statusFlags |= c.flag;
-  }
-}
-
-function newContext(errOutput, retStatusObj) {
-  retStatusObj.statusMsg = "";
-  retStatusObj.errorMsg = "";
-  retStatusObj.extendedStatus = "";
-  retStatusObj.blockSeparation = "";
-  retStatusObj.encryptedFileName = null;
-
-  return {
-    errOutput: errOutput,
-    retStatusObj: retStatusObj,
-    errArray: [],
-    statusArray: [],
-    errCode: 0,
-    detectedCard: null,
-    requestedCard: null,
-    errorMsg: "",
-    statusPat: /^\[GNUPG:\] /,
-    statusFlags: 0,
-    plaintextCount: 0,
-    withinCryptoMsg: false,
-    cryptoStartPat: /^BEGIN_DECRYPTION/,
-    cryptoEndPat: /^END_DECRYPTION/,
-    plaintextPat: /^PLAINTEXT /,
-    plaintextLengthPat: /^PLAINTEXT_LENGTH /
-  };
-}
-
-function splitErrorOutput(errOutput) {
-  var errLines = errOutput.split(/\r?\n/);
-
-  // Discard last null string, if any
-  if ((errLines.length > 1) && !errLines[errLines.length - 1]) {
-    errLines.pop();
-  }
-
-  return errLines;
-}
-
-function parseErrorLine(errLine, c) {
-  if (errLine.search(c.statusPat) === 0) {
-    // status line
-    c.statusLine = errLine.replace(c.statusPat, "");
-    c.statusArray.push(c.statusLine);
-
-    // extract first word as flag
-    var matches = c.statusLine.match(/^((\w+)\b)/);
-
-    if (matches && (matches.length > 1)) {
-      let isError = (matches[1] == "ERROR");
-      (isError ? handleError : handleFailure)(c, matches[1]);
-    }
-  } else {
-    // non-status line (details of previous status command)
-    if (!getEnigmailGpg().getGpgFeature("decryption-info")) {
-      if (errLine == "gpg: WARNING: message was not integrity protected") {
-        // workaround for Gpg < 2.0.19 that don't print DECRYPTION_INFO
-        c.statusFlags |= EnigmailConstants.DECRYPTION_FAILED;
-        c.inDecryptionFailed = true;
-      }
-    }
-
-    c.errArray.push(errLine);
-    // save details of DECRYPTION_FAILED message ass error message
-    if (c.inDecryptionFailed) {
-      c.errorMsg += errLine;
-    }
-  }
-}
-
-function detectForgedInsets(c) {
-  // detect forged message insets
-  let hasUnencryptedText = false;
-  let hasEncryptedPart = false;
-  for (var j = 0; j < c.statusArray.length; j++) {
-    if (c.statusArray[j].search(c.cryptoStartPat) === 0) {
-      c.withinCryptoMsg = true;
-      hasEncryptedPart = true;
-    } else if (c.withinCryptoMsg && c.statusArray[j].search(c.cryptoEndPat) === 0) {
-      c.withinCryptoMsg = false;
-    } else if (c.statusArray[j].search(c.plaintextPat) === 0) {
-      if (!c.withinCryptoMsg) hasUnencryptedText = true;
-
-      ++c.plaintextCount;
-      if ((c.statusArray.length > j + 1) && (c.statusArray[j + 1].search(c.plaintextLengthPat) === 0)) {
-        var matches = c.statusArray[j + 1].match(/(\w+) (\d+)/);
-        if (matches.length >= 3) {
-          c.retStatusObj.blockSeparation += (c.withinCryptoMsg ? "1" : "0") + ":" + matches[2] + " ";
-        }
-      } else {
-        // strange: we got PLAINTEXT XX, but not PLAINTEXT_LENGTH XX
-        c.retStatusObj.blockSeparation += (c.withinCryptoMsg ? "1" : "0") + ":0 ";
-      }
-    }
-  }
-  if (c.plaintextCount > 1 || (hasEncryptedPart && hasUnencryptedText)) {
-    c.statusFlags |= (EnigmailConstants.DECRYPTION_FAILED | EnigmailConstants.BAD_SIGNATURE);
-  }
-}
-
-function buildErrorMessageForCardCtrl(c, errCode, detectedCard) {
-  var errorMsg = "";
-  switch (errCode) {
-    case 1:
-      if (detectedCard) {
-        errorMsg = EnigmailLocale.getString("sc.wrongCardAvailable", [c.detectedCard, c.requestedCard]);
-      } else {
-        errorMsg = EnigmailLocale.getString("sc.insertCard", [c.requestedCard]);
-      }
-      break;
-    case 2:
-      errorMsg = EnigmailLocale.getString("sc.removeCard");
-      break;
-    case 4:
-      errorMsg = EnigmailLocale.getString("sc.noCardAvailable");
-      break;
-    case 5:
-      errorMsg = EnigmailLocale.getString("sc.noReaderAvailable");
-      break;
-  }
-  return errorMsg;
-}
+const getEnigmailKeyRing = EnigmailLazy.loader(
+  "enigmail/keyRing.jsm",
+  "EnigmailKeyRing"
+);
+const getEnigmailFiles = EnigmailLazy.loader(
+  "enigmail/files.jsm",
+  "EnigmailFiles"
+);
+const getEnigmailRNG = EnigmailLazy.loader("enigmail/rng.jsm", "EnigmailRNG");
 
 var EnigmailErrorHandling = {
   /**
    * Determin why a given key or userID cannot be used for signing
    *
    * @param keySpec String - key ID or user ID
    *
    * @return String - the reason(s) as message to display to the user
    *                  "" in case the key is valid
    */
-  determineInvSignReason: function(keySpec) {
-    EnigmailLog.DEBUG("errorHandling.jsm: determineInvSignReason: keySpec: " + keySpec + "\n");
+  determineInvSignReason(keySpec) {
+    EnigmailLog.DEBUG(
+      "errorHandling.jsm: determineInvSignReason: keySpec: " + keySpec + "\n"
+    );
 
     let reasonMsg = "";
 
     if (keySpec.search(/^(0x)?[0-9A-F]+$/) === 0) {
       let key = getEnigmailKeyRing().getKeyById(keySpec);
       if (!key) {
         reasonMsg = EnigmailLocale.getString("keyError.keyIdNotFound", keySpec);
       } else {
         let r = key.getSigningValidity();
-        if (!r.keyValid) reasonMsg = r.reason;
+        if (!r.keyValid) {
+          reasonMsg = r.reason;
+        }
       }
     } else {
       let keys = getEnigmailKeyRing().getKeysByUserId(keySpec);
       if (!keys || keys.length === 0) {
-        reasonMsg = EnigmailLocale.getString("keyError.keySpecNotFound", keySpec);
+        reasonMsg = EnigmailLocale.getString(
+          "keyError.keySpecNotFound",
+          keySpec
+        );
       } else {
         for (let i in keys) {
           let r = keys[i].getSigningValidity();
-          if (!r.keyValid) reasonMsg += r.reason + "\n";
+          if (!r.keyValid) {
+            reasonMsg += r.reason + "\n";
+          }
         }
       }
     }
 
     return reasonMsg;
   },
 
   /**
    * Determin why a given key or userID cannot be used for encryption
    *
    * @param keySpec String - key ID or user ID
    *
    * @return String - the reason(s) as message to display to the user
    *                  "" in case the key is valid
    */
-  determineInvRcptReason: function(keySpec) {
-    EnigmailLog.DEBUG("errorHandling.jsm: determineInvRcptReason: keySpec: " + keySpec + "\n");
+  determineInvRcptReason(keySpec) {
+    EnigmailLog.DEBUG(
+      "errorHandling.jsm: determineInvRcptReason: keySpec: " + keySpec + "\n"
+    );
 
     let reasonMsg = "";
 
     if (keySpec.search(/^(0x)?[0-9A-F]+$/) === 0) {
       let key = getEnigmailKeyRing().getKeyById(keySpec);
       if (!key) {
         reasonMsg = EnigmailLocale.getString("keyError.keyIdNotFound", keySpec);
       } else {
         let r = key.getEncryptionValidity();
-        if (!r.keyValid) reasonMsg = r.reason;
+        if (!r.keyValid) {
+          reasonMsg = r.reason;
+        }
       }
     } else {
       let keys = getEnigmailKeyRing().getKeysByUserId(keySpec);
       if (!keys || keys.length === 0) {
-        reasonMsg = EnigmailLocale.getString("keyError.keySpecNotFound", keySpec);
+        reasonMsg = EnigmailLocale.getString(
+          "keyError.keySpecNotFound",
+          keySpec
+        );
       } else {
         for (let i in keys) {
           let r = keys[i].getEncryptionValidity();
-          if (!r.keyValid) reasonMsg += r.reason + "\n";
+          if (!r.keyValid) {
+            reasonMsg += r.reason + "\n";
+          }
         }
       }
     }
 
     return reasonMsg;
   },
 
   /**
    * Get a unique file to use for logging with --log-file
    */
-  getTempLogFile: function() {
-    let logFile = getEnigmailFiles().getTempDirObj().clone();
+  getTempLogFile() {
+    let logFile = getEnigmailFiles()
+      .getTempDirObj()
+      .clone();
     logFile.normalize();
     logFile.append("gpgOutput." + getEnigmailRNG().generateRandomString(6));
     return logFile;
   },
 
-
   /**
    * Append the content of a file (such as created via --log-file) to the
    * debug log, and delete the file afterwards
    *
    * @param logFile: nsIFile object
    */
-  appendLogFileToDebug: function(logFile) {
+  appendLogFileToDebug(logFile) {
     if (logFile && logFile.exists() && logFile.isFile()) {
       let logData = getEnigmailFiles().readFile(logFile);
 
-      EnigmailLog.DEBUG(`errorHandling.jsm: Process terminated. Human-readable output from gpg:\n-----\n${logData}-----\n`);
+      EnigmailLog.DEBUG(
+        `errorHandling.jsm: Process terminated. Human-readable output from gpg:\n-----\n${logData}-----\n`
+      );
       try {
         logFile.remove(false);
       } catch (ex) {}
     }
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/events.jsm
+++ b/mail/extensions/openpgp/content/modules/events.jsm
@@ -1,33 +1,38 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailEvents"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
 
 /**** DEPRECATED - use EnigmailTimer instead *****/
 
 var EnigmailEvents = {
   /**
    * dispatch event aynchronously to the main thread
    *
    * @callbackFunction: Function - any function specification
    * @sleepTimeMs:      Number - optional number of miliseconds to delay
    *                             (0 if not specified)
    * @arrayOfArgs:      Array - arguments to pass to callbackFunction
    */
-  dispatchEvent: function(callbackFunction, sleepTimeMs, arrayOfArgs) {
-    EnigmailLog.DEBUG("enigmailCommon.jsm: dispatchEvent f=" + callbackFunction.name + "\n");
+  dispatchEvent(callbackFunction, sleepTimeMs, arrayOfArgs) {
+    EnigmailLog.DEBUG(
+      "enigmailCommon.jsm: dispatchEvent f=" + callbackFunction.name + "\n"
+    );
 
     return EnigmailTimer.setTimeout(() => {
       callbackFunction(arrayOfArgs);
     }, sleepTimeMs);
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/files.jsm
+++ b/mail/extensions/openpgp/content/modules/files.jsm
@@ -1,36 +1,40 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailFiles"];
 
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-Components.utils.importGlobalProperties(["TextDecoder"]);
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
 
-const {
-  OS
-} = ChromeUtils.import("resource://gre/modules/osfile.jsm", {});
+const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm", {});
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const lazyStream = EnigmailLazy.loader("enigmail/streams.jsm", "EnigmailStreams");
+const lazyStream = EnigmailLazy.loader(
+  "enigmail/streams.jsm",
+  "EnigmailStreams"
+);
 const lazyLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
 
 const NS_FILE_CONTRACTID = "@mozilla.org/file/local;1";
-const NS_LOCALFILEOUTPUTSTREAM_CONTRACTID = "@mozilla.org/network/file-output-stream;1";
-const NS_IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
-const NS_SCRIPTABLEINPUTSTREAM_CONTRACTID = "@mozilla.org/scriptableinputstream;1";
+const NS_LOCALFILEOUTPUTSTREAM_CONTRACTID =
+  "@mozilla.org/network/file-output-stream;1";
 const DIRSERVICE_CONTRACTID = "@mozilla.org/file/directory_service;1";
 
 const NS_RDONLY = 0x01;
 const NS_WRONLY = 0x02;
 const NS_CREATE_FILE = 0x08;
 const NS_TRUNCATE = 0x20;
 const DEFAULT_FILE_PERMS = 0o600;
 
@@ -44,223 +48,251 @@ function potentialWindowsExecutable(file
 var EnigmailFiles = {
   /**
    * potentialWindowsExecutable appends .exe to a file
    *
    * @param     String  file    - file path or executable name to append .exe to
    *
    * @return    String  file    - modified file path or executable name
    */
-  potentialWindowsExecutable: potentialWindowsExecutable,
+  potentialWindowsExecutable,
 
-  isAbsolutePath: function(filePath, isDosLike) {
+  isAbsolutePath(filePath, isDosLike) {
     // Check if absolute path
     if (isDosLike) {
-      return ((filePath.search(/^\w+:\\/) === 0) || (filePath.search(/^\\\\/) === 0) ||
-        (filePath.search(/^\/\//) === 0));
+      return (
+        filePath.search(/^\w+:\\/) === 0 ||
+        filePath.search(/^\\\\/) === 0 ||
+        filePath.search(/^\/\//) === 0
+      );
     }
-    else {
-      return (filePath.search(/^\//) === 0);
-    }
+
+    return filePath.search(/^\//) === 0;
   },
 
   /**
    * resolvePathWithEnv tries to resolve an file's path with the environment PATH variable.
    *
    * @param     String  file        - file to be resolved
    *
    * @return    String  foundPath   - Returns found path. If no path is found, returns null.
    */
-  resolvePathWithEnv: function(executable) {
-    let envSvc = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
-    const foundPath = EnigmailFiles.resolvePath(potentialWindowsExecutable(executable), envSvc.get("PATH"), EnigmailOS.isDosLike);
+  resolvePathWithEnv(executable) {
+    let envSvc = Cc["@mozilla.org/process/environment;1"].getService(
+      Ci.nsIEnvironment
+    );
+    const foundPath = EnigmailFiles.resolvePath(
+      potentialWindowsExecutable(executable),
+      envSvc.get("PATH"),
+      EnigmailOS.isDosLike
+    );
     if (foundPath !== null) {
       foundPath.normalize();
     }
     return foundPath;
   },
 
-  resolvePath: function(filePath, envPath, isDosLike) {
+  resolvePath(filePath, envPath, isDosLike) {
     lazyLog().DEBUG("files.jsm: resolvePath: filePath=" + filePath + "\n");
 
-    if (EnigmailFiles.isAbsolutePath(filePath, isDosLike))
+    if (EnigmailFiles.isAbsolutePath(filePath, isDosLike)) {
       return filePath;
+    }
 
-    if (!envPath)
+    if (!envPath) {
       return null;
+    }
 
     const fileNames = filePath.split(";");
 
     const pathDirs = envPath.split(isDosLike ? ";" : ":");
 
     for (let i = 0; i < fileNames.length; i++) {
       for (let j = 0; j < pathDirs.length; j++) {
         try {
           const pathDir = Cc[NS_FILE_CONTRACTID].createInstance(Ci.nsIFile);
 
-          lazyLog().DEBUG("files.jsm: resolvePath: checking for " + pathDirs[j] + "/" + fileNames[i] + "\n");
+          lazyLog().DEBUG(
+            "files.jsm: resolvePath: checking for " +
+              pathDirs[j] +
+              "/" +
+              fileNames[i] +
+              "\n"
+          );
 
           EnigmailFiles.initPath(pathDir, pathDirs[j]);
 
           try {
             if (pathDir.exists() && pathDir.isDirectory()) {
               pathDir.appendRelativePath(fileNames[i]);
 
               if (pathDir.exists() && !pathDir.isDirectory()) {
                 return pathDir;
               }
             }
-          }
-          catch (ex) {}
-        }
-        catch (ex) {}
+          } catch (ex) {}
+        } catch (ex) {}
       }
     }
     return null;
   },
 
-  createFileStream: function(filePath, permissions) {
+  createFileStream(filePath, permissions) {
     try {
       let localFile;
       if (typeof filePath == "string") {
         localFile = Cc[NS_FILE_CONTRACTID].createInstance(Ci.nsIFile);
         EnigmailFiles.initPath(localFile, filePath);
-      }
-      else {
+      } else {
         localFile = filePath.QueryInterface(Ci.nsIFile);
       }
 
       if (localFile.exists()) {
+        if (localFile.isDirectory() || !localFile.isWritable()) {
+          throw Cr.NS_ERROR_FAILURE;
+        }
 
-        if (localFile.isDirectory() || !localFile.isWritable())
-          throw Components.results.NS_ERROR_FAILURE;
-
-        if (!permissions)
+        if (!permissions) {
           permissions = localFile.permissions;
+        }
       }
 
-      if (!permissions)
+      if (!permissions) {
         permissions = DEFAULT_FILE_PERMS;
+      }
 
       const flags = NS_WRONLY | NS_CREATE_FILE | NS_TRUNCATE;
 
-      const fileStream = Cc[NS_LOCALFILEOUTPUTSTREAM_CONTRACTID].createInstance(Ci.nsIFileOutputStream);
+      const fileStream = Cc[NS_LOCALFILEOUTPUTSTREAM_CONTRACTID].createInstance(
+        Ci.nsIFileOutputStream
+      );
 
       fileStream.init(localFile, flags, permissions, 0);
 
       return fileStream;
-
-    }
-    catch (ex) {
-      lazyLog().ERROR("files.jsm: createFileStream: Failed to create " + filePath + "\n");
+    } catch (ex) {
+      lazyLog().ERROR(
+        "files.jsm: createFileStream: Failed to create " + filePath + "\n"
+      );
       return null;
     }
   },
 
   // path initialization function
   // uses persistentDescriptor in case that initWithPath fails
   // (seems to happen frequently with UTF-8 characters in path names)
-  initPath: function(localFileObj, pathStr) {
+  initPath(localFileObj, pathStr) {
     localFileObj.initWithPath(pathStr);
 
     if (!localFileObj.exists()) {
       localFileObj.persistentDescriptor = pathStr;
     }
   },
 
   /**
    * Read the contents of a text file into a string
    *
    * @param fileObj: Object (nsIFile)
    *
    * @return String (file contents)
    */
-  readFile: function(fileObj) {
+  readFile(fileObj) {
     let fileContents = "";
 
     if (fileObj.exists()) {
-      let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+      let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+        Ci.nsIJSInspector
+      );
 
-      let decoder = new TextDecoder();
-      OS.File.read(fileObj.path).then(arr => {
-        fileContents = EnigmailData.arrayBufferToString(arr); // Convert the array to a text
-        inspector.exitNestedEventLoop();
-      }).catch(err => {
-        inspector.exitNestedEventLoop();
-      });
+      OS.File.read(fileObj.path)
+        .then(arr => {
+          fileContents = EnigmailData.arrayBufferToString(arr); // Convert the array to a text
+          inspector.exitNestedEventLoop();
+        })
+        .catch(err => {
+          inspector.exitNestedEventLoop();
+        });
 
       inspector.enterNestedEventLoop(0); // wait for async process to terminate
     }
 
     return fileContents;
   },
 
   /** Read the contents of a file with binary data into a string
    * @param fileObj: Object (nsIFile)
    *
    * @return String (file contents)
    */
-  readBinaryFile: function(fileObj) {
+  readBinaryFile(fileObj) {
     let fileContents = "";
 
     if (fileObj.exists()) {
-      let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+      let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+        Ci.nsIJSInspector
+      );
 
-      OS.File.read(fileObj.path).then(arr => {
-        for (let i = 0; i < arr.length; i++) {
-          fileContents += String.fromCharCode(arr[i]);
-        }
+      OS.File.read(fileObj.path)
+        .then(arr => {
+          for (let i = 0; i < arr.length; i++) {
+            fileContents += String.fromCharCode(arr[i]);
+          }
 
-        inspector.exitNestedEventLoop();
-      }).catch(err => {
-        inspector.exitNestedEventLoop();
-      });
+          inspector.exitNestedEventLoop();
+        })
+        .catch(err => {
+          inspector.exitNestedEventLoop();
+        });
 
       inspector.enterNestedEventLoop(0); // wait for async process to terminate
     }
 
     return fileContents;
   },
 
-  formatCmdLine: function(command, args) {
+  formatCmdLine(command, args) {
     function getQuoted(str) {
       str = str.toString();
 
       let i = str.indexOf(" ");
       if (i >= 0) {
         return '"' + str + '"';
       }
-      else {
-        return str;
-      }
+
+      return str;
     }
 
     if (command instanceof Ci.nsIFile) {
       command = EnigmailFiles.getFilePathDesc(command);
     }
 
     const cmdStr = getQuoted(command) + " ";
-    const argStr = args.map(getQuoted).join(" ").replace(/\\\\/g, '\\');
+    const argStr = args
+      .map(getQuoted)
+      .join(" ")
+      .replace(/\\\\/g, "\\");
     return cmdStr + argStr;
   },
 
-  getFilePathDesc: function(nsFileObj) {
+  getFilePathDesc(nsFileObj) {
     if (EnigmailOS.getOS() == "WINNT") {
       return nsFileObj.persistentDescriptor;
     }
-    else {
-      return nsFileObj.path;
-    }
+
+    return nsFileObj.path;
   },
 
-  getFilePath: function(nsFileObj) {
-    return EnigmailData.convertToUnicode(EnigmailFiles.getFilePathDesc(nsFileObj), "utf-8");
+  getFilePath(nsFileObj) {
+    return EnigmailData.convertToUnicode(
+      EnigmailFiles.getFilePathDesc(nsFileObj),
+      "utf-8"
+    );
   },
 
-  getEscapedFilename: function(fileNameStr) {
+  getEscapedFilename(fileNameStr) {
     if (EnigmailOS.isDosLike) {
       // escape the backslashes and the " character (for Windows and OS/2)
       fileNameStr = fileNameStr.replace(/([\\"])/g, "\\$1");
     }
 
     if (EnigmailOS.getOS() == "WINNT") {
       // replace leading "\\" with "//"
       fileNameStr = fileNameStr.replace(/^\\\\*/, "//");
@@ -268,63 +300,61 @@ var EnigmailFiles = {
     return fileNameStr;
   },
 
   /**
    * get the temporary folder
    *
    * @return nsIFile object holding a reference to the temp directory
    */
-  getTempDirObj: function() {
+  getTempDirObj() {
     const TEMPDIR_PROP = "TmpD";
 
     try {
-      const dsprops = Cc[DIRSERVICE_CONTRACTID].getService().
-      QueryInterface(Ci.nsIProperties);
+      const dsprops = Cc[DIRSERVICE_CONTRACTID].getService().QueryInterface(
+        Ci.nsIProperties
+      );
       return dsprops.get(TEMPDIR_PROP, Ci.nsIFile);
-    }
-    catch (ex) {
+    } catch (ex) {
       // let's guess ...
       const tmpDirObj = Cc[NS_FILE_CONTRACTID].createInstance(Ci.nsIFile);
       if (EnigmailOS.getOS() == "WINNT") {
         tmpDirObj.initWithPath("C:/TEMP");
-      }
-      else {
+      } else {
         tmpDirObj.initWithPath("/tmp");
       }
       return tmpDirObj;
     }
   },
 
   /**
    * get the temporary folder as string
    *
    * @return String containing the temp directory name
    */
-  getTempDir: function() {
+  getTempDir() {
     return EnigmailFiles.getTempDirObj().path;
   },
 
   /**
    * create a new folder as subfolder of the temporary directory
    *
    * @param dirName  String  - name of subfolder
    * @param unique   Boolean - if true, the directory is guaranteed to be unique
    *
    * @return nsIFile object holding a reference to the created directory
    */
-  createTempSubDir: function(dirName, unique = false) {
+  createTempSubDir(dirName, unique = false) {
     const localFile = EnigmailFiles.getTempDirObj().clone();
 
     localFile.append(dirName);
     if (unique) {
-      localFile.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */ );
-    }
-    else {
-      localFile.create(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */ );
+      localFile.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */);
+    } else {
+      localFile.create(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */);
     }
 
     return localFile;
   },
 
   /**
    * Ensure that a directory exists and is writeable.
    *
@@ -332,165 +362,170 @@ var EnigmailFiles = {
    * @param permissions Number - file permissions in Unix style (e.g. 0700)
    *
    * @return Number:
    *    0 - OK: directory exists (or was created) and is writeable
    *    1 - NOK: Directory does not exist (and cannot be created)
    *    2 - NOK: Directory exists but is readonly (and cannot be modified)
    *    3 - NOK: File object with required name exists but is not a directory
    */
-  ensureWritableDirectory: function(dirObj, permissions) {
+  ensureWritableDirectory(dirObj, permissions) {
     let retVal = -1;
     try {
       if (dirObj.isDirectory()) {
         try {
           if (dirObj.isWritable()) {
             retVal = 0;
-          }
-          else {
+          } else {
             dirObj.permissions = permissions;
             retVal = 0;
           }
-        }
-        catch (x) {
+        } catch (x) {
           retVal = 2;
         }
-      }
-      else {
+      } else {
         retVal = 3;
       }
-    }
-    catch (x) {
+    } catch (x) {
       // directory doesn't exist
       try {
         dirObj.create(Ci.nsIFile.DIRECTORY_TYPE, permissions);
         retVal = 0;
-      }
-      catch (x2) {
+      } catch (x2) {
         retVal = 1;
       }
     }
     return retVal;
   },
 
-
   /**
    *  Write data to a file
    *  @filePath |string| or |nsIFile| object - the file to be created
    *  @data     |string|       - the data to write to the file
    *  @permissions  |number|   - file permissions according to Unix spec (0600 by default)
    *
    *  @return true if data was written successfully, false otherwise
    */
-  writeFileContents: function(filePath, data, permissions) {
+  writeFileContents(filePath, data, permissions) {
     try {
-      const fileOutStream = EnigmailFiles.createFileStream(filePath, permissions);
+      const fileOutStream = EnigmailFiles.createFileStream(
+        filePath,
+        permissions
+      );
 
       if (data.length) {
         if (fileOutStream.write(data, data.length) != data.length) {
-          throw Components.results.NS_ERROR_FAILURE;
+          throw Cr.NS_ERROR_FAILURE;
         }
 
         fileOutStream.flush();
       }
       fileOutStream.close();
-    }
-    catch (ex) {
-      lazyLog().ERROR("files.jsm: writeFileContents: Failed to write to " + filePath + "\n");
+    } catch (ex) {
+      lazyLog().ERROR(
+        "files.jsm: writeFileContents: Failed to write to " + filePath + "\n"
+      );
       return false;
     }
 
     return true;
   },
 
   /**
    * Create a text file from the contents of a given URL
    *
    * @param srcUrl:  String         - the URL to download
    * @param outFile: nsIFile object - the file to create
    *
    * no return value
    */
-  writeUrlToFile: function(srcUrl, outFile) {
+  writeUrlToFile(srcUrl, outFile) {
     lazyLog().DEBUG("files.jsm: writeUrlToFile(" + outFile.path + ")\n");
 
-    var ioServ = Cc[NS_IOSERVICE_CONTRACTID].getService(Ci.nsIIOService);
-    var msgUri = ioServ.newURI(srcUrl, null, null);
+    var msgUri = Services.io.newURI(srcUrl);
     var channel = lazyStream().createChannel(msgUri);
     var istream = channel.open();
 
-    var fstream = Cc["@mozilla.org/network/safe-file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
-    var buffer = Cc["@mozilla.org/network/buffered-output-stream;1"].createInstance(Ci.nsIBufferedOutputStream);
+    var fstream = Cc[
+      "@mozilla.org/network/safe-file-output-stream;1"
+    ].createInstance(Ci.nsIFileOutputStream);
+    var buffer = Cc[
+      "@mozilla.org/network/buffered-output-stream;1"
+    ].createInstance(Ci.nsIBufferedOutputStream);
     fstream.init(outFile, 0x04 | 0x08 | 0x20, 0x180, 0); // write, create, truncate
     buffer.init(fstream, 8192);
 
     while (istream.available() > 0) {
       buffer.writeFrom(istream, istream.available());
     }
 
     // Close the output streams
-    if (buffer instanceof Ci.nsISafeOutputStream)
+    if (buffer instanceof Ci.nsISafeOutputStream) {
       buffer.finish();
-    else
+    } else {
       buffer.close();
+    }
 
-    if (fstream instanceof Ci.nsISafeOutputStream)
+    if (fstream instanceof Ci.nsISafeOutputStream) {
       fstream.finish();
-    else
+    } else {
       fstream.close();
+    }
 
     // Close the input stream
     istream.close();
   },
 
   // return the useable path (for gpg) of a file object
-  getFilePathReadonly: function(nsFileObj, creationMode) {
-    if (creationMode === null) creationMode = NS_RDONLY;
+  getFilePathReadonly(nsFileObj, creationMode) {
+    if (creationMode === null) {
+      creationMode = NS_RDONLY;
+    }
     return nsFileObj.path;
   },
 
   /**
    * Create an empty ZIP file
    *
    * @param nsFileObj - nsIFile object: reference to the file to be created
    *
    * @return nsIZipWriter object allow to perform write operations on the ZIP file
    */
-  createZipFile: function(nsFileObj) {
-    const zipW = Cc['@mozilla.org/zipwriter;1'].createInstance(Ci.nsIZipWriter);
+  createZipFile(nsFileObj) {
+    const zipW = Cc["@mozilla.org/zipwriter;1"].createInstance(Ci.nsIZipWriter);
     zipW.open(nsFileObj, NS_WRONLY | NS_CREATE_FILE | NS_TRUNCATE);
 
     return zipW;
   },
 
   /**
    * Open a ZIP file for reading
    *
    * @param nsFileObj - nsIFile object: reference to the file to be created
    *
    * @return nsIZipReader object allow to perform read operations on the ZIP file
    */
-  openZipFile: function(nsFileObj) {
-    const zipR = Cc['@mozilla.org/libjar/zip-reader;1'].createInstance(Ci.nsIZipReader);
+  openZipFile(nsFileObj) {
+    const zipR = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(
+      Ci.nsIZipReader
+    );
     zipR.open(nsFileObj);
 
     return zipR;
   },
 
-
   /**
    * Unpack a ZIP file to a directory
    *
    * @param zipFile   - nsIZipReader object: file to be extracted
    * @param targetDir - nsIFile object:      target directory
    *
    * @return Boolean: true if extraction successfull, false otherwise
    */
-  extractZipFile: function(zipFile, targetDir) {
-
+  extractZipFile(zipFile, targetDir) {
     // create missing parent directories
     function createDirWithParents(dirObj) {
       if (!dirObj.parent.exists()) {
         createDirWithParents(dirObj.parent);
       }
       dirObj.create(dirObj.DIRECTORY_TYPE, 493);
     }
 
@@ -499,33 +534,33 @@ var EnigmailFiles = {
       let f = zipReader.findEntries("*");
 
       for (let i of f) {
         let t = targetDir.clone();
         let entry = zipReader.getEntry(i);
 
         if (!EnigmailOS.isDosLike) {
           t.initWithPath(t.path + "/" + i);
-        }
-        else {
+        } else {
           i = i.replace(/\//g, "\\");
           t.initWithPath(t.path + "\\" + i);
         }
 
         if (!t.parent.exists()) {
           createDirWithParents(t.parent);
         }
 
         if (!(entry.isDirectory || i.search(/[\/\\]$/) >= 0)) {
           zipReader.extract(i, t);
         }
       }
 
       zipReader.close();
 
       return true;
-    }
-    catch (ex) {
-      lazyLog().ERROR("files.jsm: extractZipFile: Failed to create ZIP: " + ex + "\n");
+    } catch (ex) {
+      lazyLog().ERROR(
+        "files.jsm: extractZipFile: Failed to create ZIP: " + ex + "\n"
+      );
       return false;
     }
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/filters.jsm
+++ b/mail/extensions/openpgp/content/modules/filters.jsm
@@ -3,449 +3,514 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailFilters"];
 
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailPersistentCrypto = ChromeUtils.import("chrome://openpgp/content/modules/persistentCrypto.jsm").EnigmailPersistentCrypto;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailPersistentCrypto = ChromeUtils.import(
+  "chrome://openpgp/content/modules/persistentCrypto.jsm"
+).EnigmailPersistentCrypto;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
 const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm").NetUtil;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm")
+  .NetUtil;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
 
 const getDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
 
 var gNewMailListenerInitiated = false;
 
 /**
  * filter action for creating a decrypted version of the mail and
  * deleting the original mail at the same time
  */
 
 const filterActionMoveDecrypt = {
-  apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
-
-    EnigmailLog.DEBUG("filters.jsm: filterActionMoveDecrypt: Move to: " + aActionValue + "\n");
+  apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: filterActionMoveDecrypt: Move to: " + aActionValue + "\n"
+    );
 
     var msgHdrs = [];
 
     for (var i = 0; i < aMsgHdrs.length; i++) {
       msgHdrs.push(aMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr));
     }
 
-    EnigmailPersistentCrypto.dispatchMessages(msgHdrs, aActionValue, aListener, true);
+    EnigmailPersistentCrypto.dispatchMessages(
+      msgHdrs,
+      aActionValue,
+      aListener,
+      true
+    );
   },
 
-  isValidForType: function(type, scope) {
+  isValidForType(type, scope) {
     return true;
   },
 
-  validateActionValue: function(value, folder, type) {
-    getDialog().alert(null, EnigmailLocale.getString("filter.decryptMove.warnExperimental"));
+  validateActionValue(value, folder, type) {
+    getDialog().alert(
+      null,
+      EnigmailLocale.getString("filter.decryptMove.warnExperimental")
+    );
 
     if (value === "") {
       return EnigmailLocale.getString("filter.folderRequired");
     }
 
     return null;
-  }
+  },
 };
 
 /**
  * filter action for creating a decrypted copy of the mail, leaving the original
  * message untouched
  */
 const filterActionCopyDecrypt = {
-  apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
-    EnigmailLog.DEBUG("filters.jsm: filterActionCopyDecrypt: Copy to: " + aActionValue + "\n");
+  apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: filterActionCopyDecrypt: Copy to: " + aActionValue + "\n"
+    );
 
     var msgHdrs = [];
 
     for (var i = 0; i < aMsgHdrs.length; i++) {
       msgHdrs.push(aMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr));
     }
 
-    EnigmailPersistentCrypto.dispatchMessages(msgHdrs, aActionValue, aListener, false);
+    EnigmailPersistentCrypto.dispatchMessages(
+      msgHdrs,
+      aActionValue,
+      aListener,
+      false
+    );
   },
 
-  isValidForType: function(type, scope) {
-    EnigmailLog.DEBUG("filters.jsm: filterActionCopyDecrypt.isValidForType(" + type + ")\n");
+  isValidForType(type, scope) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: filterActionCopyDecrypt.isValidForType(" + type + ")\n"
+    );
 
     let r = true;
     return r;
   },
 
-  validateActionValue: function(value, folder, type) {
-    EnigmailLog.DEBUG("filters.jsm: filterActionCopyDecrypt.validateActionValue(" + value + ")\n");
+  validateActionValue(value, folder, type) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: filterActionCopyDecrypt.validateActionValue(" +
+        value +
+        ")\n"
+    );
 
     if (value === "") {
       return EnigmailLocale.getString("filter.folderRequired");
     }
 
     return null;
-  }
+  },
 };
 
 /**
  * filter action for to encrypt a mail to a specific key
  */
 const filterActionEncrypt = {
-  apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+  apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
     // Ensure KeyRing is loaded.
     if (aMsgWindow) {
       EnigmailCore.getService(aMsgWindow.domWindow);
-    }
-    else {
+    } else {
       EnigmailCore.getService();
     }
     EnigmailKeyRing.getAllKeys();
 
-    EnigmailLog.DEBUG("filters.jsm: filterActionEncrypt: Encrypt to: " + aActionValue + "\n");
+    EnigmailLog.DEBUG(
+      "filters.jsm: filterActionEncrypt: Encrypt to: " + aActionValue + "\n"
+    );
     let keyObj = EnigmailKeyRing.getKeyById(aActionValue);
 
     if (keyObj === null) {
-      EnigmailLog.DEBUG("filters.jsm: failed to find key by id: " + aActionValue + "\n");
+      EnigmailLog.DEBUG(
+        "filters.jsm: failed to find key by id: " + aActionValue + "\n"
+      );
       let keyId = EnigmailKeyRing.getValidKeyForRecipient(aActionValue);
       if (keyId) {
         keyObj = EnigmailKeyRing.getKeyById(keyId);
       }
     }
 
     if (keyObj === null && aListener) {
       EnigmailLog.DEBUG("filters.jsm: no valid key - aborting\n");
 
       aListener.OnStartCopy();
       aListener.OnStopCopy(1);
 
       return;
     }
 
-    EnigmailLog.DEBUG("filters.jsm: key to encrypt to: " + JSON.stringify(keyObj) + ", userId: " + keyObj.userId + "\n");
+    EnigmailLog.DEBUG(
+      "filters.jsm: key to encrypt to: " +
+        JSON.stringify(keyObj) +
+        ", userId: " +
+        keyObj.userId +
+        "\n"
+    );
 
     var msgHdrs = [];
     for (let i = 0; i < aMsgHdrs.length; i++) {
       let msg = aMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr);
       // Maybe skip messages here if they are already encrypted to
       // the target key? There might be some use case for unconditionally
       // encrypting here. E.g. to use the local preferences and remove all
       // other recipients.
       // Also not encrypting to already encrypted messages would make the
       // behavior less transparent as it's not obvious.
       msgHdrs.push(msg);
     }
 
     if (msgHdrs.length) {
-      EnigmailPersistentCrypto.dispatchMessages(msgHdrs, null /* same folder */ , aListener,
-        true /* move */ , keyObj /* target key */ );
+      EnigmailPersistentCrypto.dispatchMessages(
+        msgHdrs,
+        null /* same folder */,
+        aListener,
+        true /* move */,
+        keyObj /* target key */
+      );
     }
   },
 
-  isValidForType: function(type, scope) {
+  isValidForType(type, scope) {
     return true;
   },
 
-  validateActionValue: function(value, folder, type) {
+  validateActionValue(value, folder, type) {
     // Initialize KeyRing. Ugly as it blocks the GUI but
     // we need it.
     EnigmailCore.getService();
     EnigmailKeyRing.getAllKeys();
 
-    EnigmailLog.DEBUG("filters.jsm: validateActionValue: Encrypt to: " + value + "\n");
+    EnigmailLog.DEBUG(
+      "filters.jsm: validateActionValue: Encrypt to: " + value + "\n"
+    );
     if (value === "") {
       return EnigmailLocale.getString("filter.keyRequired");
     }
 
     let keyObj = EnigmailKeyRing.getKeyById(value);
 
     if (keyObj === null) {
-      EnigmailLog.DEBUG("filters.jsm: failed to find key by id. Looking for uid.\n");
+      EnigmailLog.DEBUG(
+        "filters.jsm: failed to find key by id. Looking for uid.\n"
+      );
       let keyId = EnigmailKeyRing.getValidKeyForRecipient(value);
       if (keyId) {
         keyObj = EnigmailKeyRing.getKeyById(keyId);
       }
     }
 
     if (keyObj === null) {
       return EnigmailLocale.getString("filter.keyNotFound", [value]);
     }
 
     if (!keyObj.secretAvailable) {
       // We warn but we allow it. There might be use cases where
       // thunderbird + enigmail is used as a gateway filter with
       // the secret not available on one machine and the decryption
       // is intended to happen on different systems.
-      getDialog().alert(null, EnigmailLocale.getString("filter.warn.keyNotSecret", [value]));
+      getDialog().alert(
+        null,
+        EnigmailLocale.getString("filter.warn.keyNotSecret", [value])
+      );
     }
 
     return null;
-  }
+  },
 };
 
 function isPGPEncrypted(data) {
   // We only check the first mime subpart for application/pgp-encrypted.
   // If it is text/plain or text/html we look into that for the
   // message marker.
   // If there are no subparts we just look in the body.
   //
   // This intentionally does not match more complex cases
   // with sub parts beeing encrypted etc. as auto processing
   // these kinds of mails will be error prone and better not
   // done through a filter
 
   var mimeTree = EnigmailMime.getMimeTree(data, true);
-  if (!(mimeTree.subParts.length)) {
+  if (!mimeTree.subParts.length) {
     // No subParts. Check for PGP Marker in Body
-    return mimeTree.body.indexOf('-----BEGIN PGP MESSAGE-----') >= 0;
+    return mimeTree.body.includes("-----BEGIN PGP MESSAGE-----");
   }
 
   // Check the type of the first subpart.
   var firstPart = mimeTree.subParts[0];
   var ct = firstPart.fullContentType;
-  if (typeof(ct) == "string") {
+  if (typeof ct == "string") {
     ct = ct.replace(/[\r\n]/g, " ");
     // Proper PGP/MIME ?
     if (ct.search(/application\/pgp-encrypted/i) >= 0) {
       return true;
     }
     // Look into text/plain pgp messages and text/html messages.
-    if (ct.search(/text\/plain/i) >= 0 ||
-      ct.search(/text\/html/i) >= 0) {
-      return firstPart.body.indexOf('-----BEGIN PGP MESSAGE-----') >= 0;
+    if (ct.search(/text\/plain/i) >= 0 || ct.search(/text\/html/i) >= 0) {
+      return firstPart.body.includes("-----BEGIN PGP MESSAGE-----");
     }
   }
   return false;
 }
 
 /**
  * filter term for OpenPGP Encrypted mail
  */
 const filterTermPGPEncrypted = {
   id: EnigmailConstants.FILTER_TERM_PGP_ENCRYPTED,
   name: EnigmailLocale.getString("filter.term.pgpencrypted.label"),
   needsBody: true,
-  match: function(aMsgHdr, searchValue, searchOp) {
+  match(aMsgHdr, searchValue, searchOp) {
     var folder = aMsgHdr.folder;
     var stream = folder.getMsgInputStream(aMsgHdr, {});
 
-    var messageSize = folder.hasMsgOffline(aMsgHdr.messageKey) ? aMsgHdr.offlineMessageSize : aMsgHdr.messageSize;
-    var scriptInput = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance();
+    var messageSize = folder.hasMsgOffline(aMsgHdr.messageKey)
+      ? aMsgHdr.offlineMessageSize
+      : aMsgHdr.messageSize;
     var data;
     try {
       data = NetUtil.readInputStreamToString(stream, messageSize);
-    }
-    catch (ex) {
-      EnigmailLog.DEBUG("filters.jsm: filterTermPGPEncrypted: failed to get data.\n");
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "filters.jsm: filterTermPGPEncrypted: failed to get data.\n"
+      );
       // If we don't know better to return false.
       stream.close();
       return false;
     }
 
     var isPGP = isPGPEncrypted(data);
 
     stream.close();
 
-    return ((searchOp == Ci.nsMsgSearchOp.Is && isPGP) ||
-      (searchOp == Ci.nsMsgSearchOp.Isnt && !isPGP));
+    return (
+      (searchOp == Ci.nsMsgSearchOp.Is && isPGP) ||
+      (searchOp == Ci.nsMsgSearchOp.Isnt && !isPGP)
+    );
   },
 
-  getEnabled: function(scope, op) {
-    return true;
-  },
-
-  getAvailable: function(scope, op) {
+  getEnabled(scope, op) {
     return true;
   },
 
-  getAvailableOperators: function(scope, length) {
+  getAvailable(scope, op) {
+    return true;
+  },
+
+  getAvailableOperators(scope, length) {
     length.value = 2;
     return [Ci.nsMsgSearchOp.Is, Ci.nsMsgSearchOp.Isnt];
-  }
+  },
 };
 
-/**
- * Add a custom filter action. If the filter already exists, do nothing
- * (for example, if addon is disabled and re-enabled)
- *
- * @param filterObj - nsIMsgFilterCustomAction
- */
-function addFilterIfNotExists(filterObj) {
-  let filterService = Cc["@mozilla.org/messenger/services/filters;1"].getService(Ci.nsIMsgFilterService);
-
-  let foundFilter = null;
-  try {
-    foundFilter = filterService.getCustomAction(filterObj.id);
-  }
-  catch (ex) {}
-
-  if (!foundFilter) {
-    EnigmailLog.DEBUG("filters.jsm: addFilterIfNotExists: " + filterObj.id + "\n");
-    filterService.addCustomAction(filterObj);
-  }
-}
-
 function initNewMailListener() {
   EnigmailLog.DEBUG("filters.jsm: initNewMailListener()\n");
 
   if (!gNewMailListenerInitiated) {
-    let notificationService = Cc["@mozilla.org/messenger/msgnotificationservice;1"]
-      .getService(Ci.nsIMsgFolderNotificationService);
-    notificationService.addListener(newMailListener, notificationService.msgAdded);
+    let notificationService = Cc[
+      "@mozilla.org/messenger/msgnotificationservice;1"
+    ].getService(Ci.nsIMsgFolderNotificationService);
+    notificationService.addListener(
+      newMailListener,
+      notificationService.msgAdded
+    );
   }
   gNewMailListenerInitiated = true;
 }
 
 function shutdownNewMailListener() {
   EnigmailLog.DEBUG("filters.jsm: shutdownNewMailListener()\n");
 
   if (gNewMailListenerInitiated) {
-    let notificationService = Cc["@mozilla.org/messenger/msgnotificationservice;1"]
-      .getService(Ci.nsIMsgFolderNotificationService);
+    let notificationService = Cc[
+      "@mozilla.org/messenger/msgnotificationservice;1"
+    ].getService(Ci.nsIMsgFolderNotificationService);
     notificationService.removeListener(newMailListener);
     gNewMailListenerInitiated = false;
   }
 }
 
 function getIdentityForSender(senderEmail, msgServer) {
-  let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+  let accountManager = Cc[
+    "@mozilla.org/messenger/account-manager;1"
+  ].getService(Ci.nsIMsgAccountManager);
 
   let identities = accountManager.getIdentitiesForServer(msgServer);
 
   for (let i = 0; i < identities.length; i++) {
     let id = identities.queryElementAt(i, Ci.nsIMsgIdentity);
     if (id.email.toLowerCase() === senderEmail.toLowerCase()) {
       return id;
     }
   }
 
   return null;
 }
 
 var consumerList = [];
 
-
 function JsmimeEmitter(requireBody) {
   this.requireBody = requireBody;
   this.mimeTree = {
     partNum: "",
     headers: null,
     body: "",
     parent: null,
-    subParts: []
+    subParts: [],
   };
   this.stack = [];
   this.currPartNum = "";
 }
 
 JsmimeEmitter.prototype = {
-
-  createPartObj: function(partNum, headers, parent) {
+  createPartObj(partNum, headers, parent) {
     return {
-      partNum: partNum,
-      headers: headers,
+      partNum,
+      headers,
       body: "",
-      parent: parent,
-      subParts: []
+      parent,
+      subParts: [],
     };
   },
 
-  getMimeTree: function() {
+  getMimeTree() {
     return this.mimeTree.subParts[0];
   },
 
   /** JSMime API **/
-  startMessage: function() {
+  startMessage() {
     this.currentPart = this.mimeTree;
   },
-  endMessage: function() {},
+  endMessage() {},
 
-  startPart: function(partNum, headers) {
-    EnigmailLog.DEBUG("filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n");
+  startPart(partNum, headers) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n"
+    );
     //this.stack.push(partNum);
     let newPart = this.createPartObj(partNum, headers, this.currentPart);
 
     if (partNum.indexOf(this.currPartNum) === 0) {
       // found sub-part
       this.currentPart.subParts.push(newPart);
-    }
-    else {
+    } else {
       // found same or higher level
       this.currentPart.subParts.push(newPart);
     }
     this.currPartNum = partNum;
     this.currentPart = newPart;
   },
 
-  endPart: function(partNum) {
-    EnigmailLog.DEBUG("filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n");
+  endPart(partNum) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n"
+    );
     this.currentPart = this.currentPart.parent;
   },
 
-  deliverPartData: function(partNum, data) {
-    EnigmailLog.DEBUG("filters.jsm: JsmimeEmitter.deliverPartData: partNum=" + partNum + "\n");
+  deliverPartData(partNum, data) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: JsmimeEmitter.deliverPartData: partNum=" + partNum + "\n"
+    );
     if (this.requireBody) {
-      if (typeof(data) === "string") {
+      if (typeof data === "string") {
         this.currentPart.body += data;
-      }
-      else {
+      } else {
         this.currentPart.body += EnigmailData.arrayBufferToString(data);
       }
     }
-  }
+  },
 };
 
 function processIncomingMail(url, requireBody, aMsgHdr) {
   EnigmailLog.DEBUG("filters.jsm: processIncomingMail()\n");
 
   let inputStream = EnigmailStreams.newStringStreamListener(msgData => {
     let opt = {
       strformat: "unicode",
-      bodyformat: "decode"
+      bodyformat: "decode",
     };
 
     try {
       let e = new JsmimeEmitter(requireBody);
       let p = new jsmime.MimeParser(e, opt);
       p.deliverData(msgData);
 
-
       for (let c of consumerList) {
         try {
           c.consumeMessage(e.getMimeTree(), msgData, aMsgHdr);
-        }
-        catch (ex) {
-          EnigmailLog.DEBUG("filters.jsm: processIncomingMail: exception: " + ex.toString() + "\n");
+        } catch (ex) {
+          EnigmailLog.DEBUG(
+            "filters.jsm: processIncomingMail: exception: " +
+              ex.toString() +
+              "\n"
+          );
         }
       }
-    }
-    catch (ex) {}
+    } catch (ex) {}
   });
 
   try {
     let channel = EnigmailStreams.createChannel(url);
     channel.asyncOpen(inputStream, null);
-  }
-  catch (e) {
-    EnigmailLog.DEBUG("filters.jsm: processIncomingMail: open stream exception " + e.toString() + "\n");
+  } catch (e) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: processIncomingMail: open stream exception " +
+        e.toString() +
+        "\n"
+    );
   }
 }
 
 function getRequireMessageProcessing(aMsgHdr) {
-  let isInbox = aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.CheckNew) || aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.Inbox);
+  let isInbox =
+    aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.CheckNew) ||
+    aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.Inbox);
   let requireBody = false;
   let inboxOnly = true;
   let selfSentOnly = false;
   let processReadMail = false;
 
   for (let c of consumerList) {
     if (!c.incomingMailOnly) {
       inboxOnly = false;
@@ -456,94 +521,110 @@ function getRequireMessageProcessing(aMs
     if (!c.headersOnly) {
       requireBody = true;
     }
     if (c.selfSentOnly) {
       selfSentOnly = true;
     }
   }
 
-  if (!processReadMail && aMsgHdr.isRead) return null;
-  if (inboxOnly && !isInbox) return null;
+  if (!processReadMail && aMsgHdr.isRead) {
+    return null;
+  }
+  if (inboxOnly && !isInbox) {
+    return null;
+  }
   if (selfSentOnly) {
     let sender = EnigmailFuncs.parseEmails(aMsgHdr.author, true);
     let id = null;
     if (sender && sender[0]) {
       id = getIdentityForSender(sender[0].email, aMsgHdr.folder.server);
     }
 
-    if (!id) return null;
+    if (!id) {
+      return null;
+    }
   }
 
-  EnigmailLog.DEBUG("filters.jsm: getRequireMessageProcessing: author: " + aMsgHdr.author + "\n");
+  EnigmailLog.DEBUG(
+    "filters.jsm: getRequireMessageProcessing: author: " + aMsgHdr.author + "\n"
+  );
 
-  let u = EnigmailCompat.getUrlFromUriSpec(aMsgHdr.folder.getUriForMsg(aMsgHdr));
+  let u = EnigmailCompat.getUrlFromUriSpec(
+    aMsgHdr.folder.getUriForMsg(aMsgHdr)
+  );
 
-  if (! u) {
+  if (!u) {
     return null;
   }
 
-  let op = (u.spec.indexOf("?") > 0 ? "&" : "?");
+  let op = u.spec.indexOf("?") > 0 ? "&" : "?";
   let url = u.spec + op + "header=enigmailFilter";
 
   return {
-    url: url,
-    requireBody: requireBody
+    url,
+    requireBody,
   };
 }
 
 const newMailListener = {
-  msgAdded: function(aMsgHdr) {
-    EnigmailLog.DEBUG("filters.jsm: newMailListener.msgAdded() - got new mail in " + aMsgHdr.folder.prettiestName + "\n");
+  msgAdded(aMsgHdr) {
+    EnigmailLog.DEBUG(
+      "filters.jsm: newMailListener.msgAdded() - got new mail in " +
+        aMsgHdr.folder.prettiestName +
+        "\n"
+    );
 
-    if (consumerList.length === 0) return;
+    if (consumerList.length === 0) {
+      return;
+    }
 
     let ret = getRequireMessageProcessing(aMsgHdr);
     if (ret) {
       processIncomingMail(ret.url, ret.requireBody, aMsgHdr);
     }
-  }
+  },
 };
 
 /**
   messageStructure - Object:
     - partNum: String                       - MIME part number
     - headers: Object(nsIStructuredHeaders) - MIME part headers
     - body: String or typedarray            - the body part
     - parent: Object(messageStructure)      - link to the parent part
     - subParts: Array of Object(messageStructure) - array of the sub-parts
  */
 
 var EnigmailFilters = {
-  onStartup: function() {
-    let filterService = Cc["@mozilla.org/messenger/services/filters;1"].getService(Ci.nsIMsgFilterService);
+  onStartup() {
+    let filterService = Cc[
+      "@mozilla.org/messenger/services/filters;1"
+    ].getService(Ci.nsIMsgFilterService);
     filterService.addCustomTerm(filterTermPGPEncrypted);
     initNewMailListener();
   },
 
-  onShutdown: function() {
+  onShutdown() {
     shutdownNewMailListener();
   },
 
   /**
    * add a new consumer to listen to new mails
    *
    * @param consumer - Object
    *   - headersOnly:      Boolean - needs full message body? [FUTURE]
    *   - incomingMailOnly: Boolean - only work on folder(s) that obtain new mail
    *                                  (Inbox and folders that listen to new mail)
    *   - unreadOnly:       Boolean - only process unread mails
    *   - selfSentOnly:     Boolean - only process mails with sender Email == Account Email
    *  - consumeMessage: function(messageStructure, rawMessageData, nsIMsgHdr)
    */
-  addNewMailConsumer: function(consumer) {
+  addNewMailConsumer(consumer) {
     EnigmailLog.DEBUG("filters.jsm: addNewMailConsumer()\n");
     consumerList.push(consumer);
   },
 
-  removeNewMailConsumer: function(consumer) {
-
-  },
+  removeNewMailConsumer(consumer) {},
 
   moveDecrypt: filterActionMoveDecrypt,
   copyDecrypt: filterActionCopyDecrypt,
-  encrypt: filterActionEncrypt
+  encrypt: filterActionEncrypt,
 };
--- a/mail/extensions/openpgp/content/modules/filtersWrapper.jsm
+++ b/mail/extensions/openpgp/content/modules/filtersWrapper.jsm
@@ -1,169 +1,188 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailFiltersWrapper"];
 
-
-
-
-
-var gNewMailListenerInitiated = false;
 var gEnigmailFilters = null;
 
-let {
-  EnigmailConstants
-} = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm");
-let {
-  EnigmailLocale
-} = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm");
+let { EnigmailConstants } = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+);
+let { EnigmailLocale } = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+);
 
 /**
  * filter action for creating a decrypted version of the mail and
  * deleting the original mail at the same time
  */
 
 const filterActionMoveDecrypt = {
   id: EnigmailConstants.FILTER_MOVE_DECRYPT,
   name: EnigmailLocale.getString("filter.decryptMove.label"),
   value: "movemessage",
-  apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
-
+  apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
     if (gEnigmailFilters) {
-      gEnigmailFilters.moveDecrypt.apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow);
-    }
-    else {
+      gEnigmailFilters.moveDecrypt.apply(
+        aMsgHdrs,
+        aActionValue,
+        aListener,
+        aType,
+        aMsgWindow
+      );
+    } else {
       aListener.OnStartCopy();
       aListener.OnStopCopy(0);
     }
   },
 
-  isValidForType: function(type, scope) {
-    return gEnigmailFilters ? gEnigmailFilters.moveDecrypt.isValidForType(type, scope) : false;
+  isValidForType(type, scope) {
+    return gEnigmailFilters
+      ? gEnigmailFilters.moveDecrypt.isValidForType(type, scope)
+      : false;
   },
 
-  validateActionValue: function(value, folder, type) {
+  validateActionValue(value, folder, type) {
     if (gEnigmailFilters) {
-      return gEnigmailFilters.moveDecrypt.validateActionValue(value, folder, type);
+      return gEnigmailFilters.moveDecrypt.validateActionValue(
+        value,
+        folder,
+        type
+      );
     }
     return null;
   },
 
   allowDuplicates: false,
   isAsync: true,
-  needsBody: true
+  needsBody: true,
 };
 
 /**
  * filter action for creating a decrypted copy of the mail, leaving the original
  * message untouched
  */
 const filterActionCopyDecrypt = {
   id: EnigmailConstants.FILTER_COPY_DECRYPT,
   name: EnigmailLocale.getString("filter.decryptCopy.label"),
   value: "copymessage",
-  apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+  apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
     if (gEnigmailFilters) {
-      gEnigmailFilters.copyDecrypt.apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow);
-    }
-    else {
+      gEnigmailFilters.copyDecrypt.apply(
+        aMsgHdrs,
+        aActionValue,
+        aListener,
+        aType,
+        aMsgWindow
+      );
+    } else {
       aListener.OnStartCopy();
       aListener.OnStopCopy(0);
     }
   },
 
-  isValidForType: function(type, scope) {
-    return gEnigmailFilters ? gEnigmailFilters.copyDecrypt.isValidForType(type, scope) : false;
+  isValidForType(type, scope) {
+    return gEnigmailFilters
+      ? gEnigmailFilters.copyDecrypt.isValidForType(type, scope)
+      : false;
   },
 
-  validateActionValue: function(value, folder, type) {
+  validateActionValue(value, folder, type) {
     if (gEnigmailFilters) {
-      return gEnigmailFilters.copyDecrypt.validateActionValue(value, folder, type);
+      return gEnigmailFilters.copyDecrypt.validateActionValue(
+        value,
+        folder,
+        type
+      );
     }
     return null;
   },
 
   allowDuplicates: false,
   isAsync: true,
-  needsBody: true
+  needsBody: true,
 };
 
 /**
  * filter action for to encrypt a mail to a specific key
  */
 const filterActionEncrypt = {
   id: EnigmailConstants.FILTER_ENCRYPT,
   name: EnigmailLocale.getString("filter.encrypt.label"),
   value: "encryptto",
-  apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+  apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
     if (gEnigmailFilters) {
-      gEnigmailFilters.encrypt.apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow);
-    }
-    else {
+      gEnigmailFilters.encrypt.apply(
+        aMsgHdrs,
+        aActionValue,
+        aListener,
+        aType,
+        aMsgWindow
+      );
+    } else {
       aListener.OnStartCopy();
       aListener.OnStopCopy(0);
     }
   },
 
-  isValidForType: function(type, scope) {
+  isValidForType(type, scope) {
     return gEnigmailFilters ? gEnigmailFilters.encrypt.isValidForType() : false;
   },
 
-  validateActionValue: function(value, folder, type) {
+  validateActionValue(value, folder, type) {
     if (gEnigmailFilters) {
       return gEnigmailFilters.encrypt.validateActionValue(value, folder, type);
     }
     return null;
-
   },
 
   allowDuplicates: false,
   isAsync: true,
-  needsBody: true
+  needsBody: true,
 };
 
-
 /**
  * Add a custom filter action. If the filter already exists, do nothing
  * (for example, if addon is disabled and re-enabled)
  *
  * @param filterObj - nsIMsgFilterCustomAction
  */
 function addFilterIfNotExists(filterObj) {
-  let filterService = Cc["@mozilla.org/messenger/services/filters;1"].getService(Ci.nsIMsgFilterService);
+  let filterService = Cc[
+    "@mozilla.org/messenger/services/filters;1"
+  ].getService(Ci.nsIMsgFilterService);
 
   let foundFilter = null;
   try {
     foundFilter = filterService.getCustomAction(filterObj.id);
-  }
-  catch (ex) {}
+  } catch (ex) {}
 
   if (!foundFilter) {
     filterService.addCustomAction(filterObj);
   }
 }
 
 var EnigmailFiltersWrapper = {
-  onStartup: function() {
-    let {
-      EnigmailFilters
-    } = ChromeUtils.import("chrome://openpgp/content/modules/filters.jsm");
+  onStartup() {
+    let { EnigmailFilters } = ChromeUtils.import(
+      "chrome://openpgp/content/modules/filters.jsm"
+    );
     gEnigmailFilters = EnigmailFilters;
 
     addFilterIfNotExists(filterActionMoveDecrypt);
     addFilterIfNotExists(filterActionCopyDecrypt);
     addFilterIfNotExists(filterActionEncrypt);
 
     gEnigmailFilters.onStartup();
   },
 
-  onShutdown: function() {
+  onShutdown() {
     gEnigmailFilters.onShutdown();
     gEnigmailFilters = null;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/fixExchangeMsg.jsm
+++ b/mail/extensions/openpgp/content/modules/fixExchangeMsg.jsm
@@ -1,197 +1,231 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailFixExchangeMsg"];
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
 
 /*
  *  Fix a broken message from MS-Exchange and replace it with the original message
  *
  * @param nsIMsgDBHdr hdr          Header of the message to fix (= pointer to message)
  * @param String brokenByApp       Type of app that created the message. Currently one of
  *                                  exchange, iPGMail
  * @param String destFolderUri     optional destination Folder URI
  *
  * @return Promise; upon success, the promise returns the messageKey
  */
 var EnigmailFixExchangeMsg = {
-  fixExchangeMessage: function(hdr, brokenByApp, destFolderUri) {
+  fixExchangeMessage(hdr, brokenByApp, destFolderUri) {
     var self = this;
-    return new Promise(
-      function fixExchangeMessage_p(resolve, reject) {
-
-        let msgUriSpec = hdr.folder.getUriForMsg(hdr);
-        EnigmailLog.DEBUG("fixExchangeMsg.jsm: fixExchangeMessage: msgUriSpec: " + msgUriSpec + "\n");
+    return new Promise(function(resolve, reject) {
+      let msgUriSpec = hdr.folder.getUriForMsg(hdr);
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: fixExchangeMessage: msgUriSpec: " +
+          msgUriSpec +
+          "\n"
+      );
 
-        self.hdr = hdr;
-        self.destFolder = hdr.folder;
-        self.resolve = resolve;
-        self.reject = reject;
-        self.brokenByApp = brokenByApp;
+      self.hdr = hdr;
+      self.destFolder = hdr.folder;
+      self.resolve = resolve;
+      self.reject = reject;
+      self.brokenByApp = brokenByApp;
 
-        if (destFolderUri) {
-          self.destFolder = EnigmailCompat.getExistingFolder(destFolderUri);
-        }
-
+      if (destFolderUri) {
+        self.destFolder = EnigmailCompat.getExistingFolder(destFolderUri);
+      }
 
-        let messenger = Cc["@mozilla.org/messenger;1"].createInstance(Ci.nsIMessenger);
-        self.msgSvc = messenger.messageServiceFromURI(msgUriSpec);
+      let messenger = Cc["@mozilla.org/messenger;1"].createInstance(
+        Ci.nsIMessenger
+      );
+      self.msgSvc = messenger.messageServiceFromURI(msgUriSpec);
 
-        let p = self.getMessageBody();
-        p.then(
-          function resolved(fixedMsgData) {
-            EnigmailLog.DEBUG("fixExchangeMsg.jsm: fixExchangeMessage: got fixedMsgData\n");
-            if (self.checkMessageStructure(fixedMsgData)) {
-              self.copyToTargetFolder(fixedMsgData);
-            } else {
-              reject();
-            }
-          });
-        p.catch(
-          function rejected(reason) {
-            EnigmailLog.DEBUG("fixExchangeMsg.jsm: fixExchangeMessage: caught rejection: " + reason + "\n");
-            reject();
-            return;
-          });
-      }
-    );
+      let p = self.getMessageBody();
+      p.then(function(fixedMsgData) {
+        EnigmailLog.DEBUG(
+          "fixExchangeMsg.jsm: fixExchangeMessage: got fixedMsgData\n"
+        );
+        if (self.checkMessageStructure(fixedMsgData)) {
+          self.copyToTargetFolder(fixedMsgData);
+        } else {
+          reject();
+        }
+      });
+      p.catch(function(reason) {
+        EnigmailLog.DEBUG(
+          "fixExchangeMsg.jsm: fixExchangeMessage: caught rejection: " +
+            reason +
+            "\n"
+        );
+        reject();
+      });
+    });
   },
 
-  getMessageBody: function() {
+  getMessageBody() {
     EnigmailLog.DEBUG("fixExchangeMsg.jsm: getMessageBody:\n");
 
     var self = this;
 
-    return new Promise(
-      function(resolve, reject) {
-        let url = EnigmailCompat.getUrlFromUriSpec(self.hdr.folder.getUriForMsg(self.hdr));
-
-        EnigmailLog.DEBUG("fixExchangeMsg.jsm: getting data from URL " + url + "\n");
-
-        let s = EnigmailStreams.newStringStreamListener(
-          function analyzeData(data) {
-            EnigmailLog.DEBUG("fixExchangeMsg.jsm: analyzeDecryptedData: got " + data.length + " bytes\n");
-
-            if (EnigmailLog.getLogLevel() > 5) {
-              EnigmailLog.DEBUG("*** start data ***\n'" + data + "'\n***end data***\n");
-            }
+    return new Promise(function(resolve, reject) {
+      let url = EnigmailCompat.getUrlFromUriSpec(
+        self.hdr.folder.getUriForMsg(self.hdr)
+      );
 
-            try {
-              let msg = self.getRepairedMessage(data);
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getting data from URL " + url + "\n"
+      );
 
-              if (msg) {
-                resolve(msg);
-              } else
-                reject(2);
-              return;
-
-            } catch (ex) {
-              reject(ex);
-            }
-          }
+      let s = EnigmailStreams.newStringStreamListener(function(data) {
+        EnigmailLog.DEBUG(
+          "fixExchangeMsg.jsm: analyzeDecryptedData: got " +
+            data.length +
+            " bytes\n"
         );
 
-        var ioServ = Components.classes[IOSERVICE_CONTRACTID].getService(Components.interfaces.nsIIOService);
-        try {
-          let channel = EnigmailStreams.createChannel(url);
-          channel.asyncOpen(s, null);
-        } catch (e) {
-          EnigmailLog.DEBUG("fixExchangeMsg.jsm: getMessageBody: exception " + e + "\n");
+        if (EnigmailLog.getLogLevel() > 5) {
+          EnigmailLog.DEBUG(
+            "*** start data ***\n'" + data + "'\n***end data***\n"
+          );
+        }
+
+        let { good, errorCode, msg } = self.getRepairedMessage(data);
+
+        if (!good) {
+          reject(errorCode);
         }
+
+        resolve(msg);
+      });
+
+      try {
+        let channel = EnigmailStreams.createChannel(url);
+        channel.asyncOpen(s, null);
+      } catch (e) {
+        EnigmailLog.DEBUG(
+          "fixExchangeMsg.jsm: getMessageBody: exception " + e + "\n"
+        );
       }
-    );
+    });
   },
 
-  getRepairedMessage: function(data) {
+  getRepairedMessage(data) {
     this.determineCreatorApp(data);
 
     let hdrEnd = data.search(/\r?\n\r?\n/);
 
     if (hdrEnd <= 0) {
       // cannot find end of header data
-      throw 0;
+      return [false, 0, ""];
     }
 
     let hdrLines = data.substr(0, hdrEnd).split(/\r?\n/);
     let hdrObj = this.getFixedHeaderData(hdrLines);
 
     if (hdrObj.headers.length === 0 || hdrObj.boundary.length === 0) {
-      throw 1;
+      return [false, 1, ""];
     }
 
     let boundary = hdrObj.boundary;
     let body;
 
     switch (this.brokenByApp) {
       case "exchange":
-        body = this.getCorrectedExchangeBodyData(data.substr(hdrEnd + 2), boundary);
+        body = this.getCorrectedExchangeBodyData(
+          data.substr(hdrEnd + 2),
+          boundary
+        );
         break;
       case "iPGMail":
-        body = this.getCorrectediPGMailBodyData(data.substr(hdrEnd + 2), boundary);
+        body = this.getCorrectediPGMailBodyData(
+          data.substr(hdrEnd + 2),
+          boundary
+        );
         break;
       default:
-        EnigmailLog.ERROR("fixExchangeMsg.jsm: getRepairedMessage: unknown appType " + self.brokenByApp + "\n");
-        throw 99;
+        EnigmailLog.ERROR(
+          "fixExchangeMsg.jsm: getRepairedMessage: unknown appType " +
+            this.brokenByApp +
+            "\n"
+        );
+        return [false, 99, ""];
     }
 
     if (body) {
-      return hdrObj.headers + "\r\n" + body;
-    } else {
-      throw 2;
+      return [true, 0, hdrObj.headers + "\r\n" + body];
     }
+    return [false, 22, ""];
   },
 
-  determineCreatorApp: function(msgData) {
+  determineCreatorApp(msgData) {
     // perform extra testing if iPGMail is assumed
-    if (this.brokenByApp === "exchange") return;
+    if (this.brokenByApp === "exchange") {
+      return;
+    }
 
     let msgTree = EnigmailMime.getMimeTree(msgData, false);
 
     try {
       let isIPGMail =
         msgTree.subParts.length === 3 &&
-        msgTree.subParts[0].headers.get("content-type").type.toLowerCase() === "text/plain" &&
-        msgTree.subParts[1].headers.get("content-type").type.toLowerCase() === "application/pgp-encrypted" &&
-        msgTree.subParts[2].headers.get("content-type").type.toLowerCase() === "text/plain";
+        msgTree.subParts[0].headers.get("content-type").type.toLowerCase() ===
+          "text/plain" &&
+        msgTree.subParts[1].headers.get("content-type").type.toLowerCase() ===
+          "application/pgp-encrypted" &&
+        msgTree.subParts[2].headers.get("content-type").type.toLowerCase() ===
+          "text/plain";
 
       if (!isIPGMail) {
         this.brokenByApp = "exchange";
       }
     } catch (x) {}
   },
 
   /**
    *  repair header data, such that they are working for PGP/MIME
    *
    *  @return: object: {
    *        headers:  String - all headers ready for appending to message
    *        boundary: String - MIME part boundary (incl. surrounding "" or '')
    *      }
    */
-  getFixedHeaderData: function(hdrLines) {
-    EnigmailLog.DEBUG("fixExchangeMsg.jsm: getFixedHeaderData: hdrLines[]:'" + hdrLines.length + "'\n");
+  getFixedHeaderData(hdrLines) {
+    EnigmailLog.DEBUG(
+      "fixExchangeMsg.jsm: getFixedHeaderData: hdrLines[]:'" +
+        hdrLines.length +
+        "'\n"
+    );
     let r = {
       headers: "",
-      boundary: ""
+      boundary: "",
     };
 
     for (let i = 0; i < hdrLines.length; i++) {
       if (hdrLines[i].search(/^content-type:/i) >= 0) {
         // Join the rest of the content type lines together.
         // See RFC 2425, section 5.8.1
         let contentTypeLine = hdrLines[i];
         i++;
@@ -210,219 +244,292 @@ var EnigmailFixExchangeMsg = {
         }
       } else {
         r.headers += hdrLines[i] + "\r\n";
       }
     }
 
     r.boundary = r.boundary.replace(/^(['"])(.*)(['"])/, "$2");
 
-    r.headers += 'Content-Type: multipart/encrypted;\r\n' +
+    r.headers +=
+      "Content-Type: multipart/encrypted;\r\n" +
       '  protocol="application/pgp-encrypted";\r\n' +
-      '  boundary="' + r.boundary + '"\r\n' +
-      'X-Enigmail-Info: Fixed broken PGP/MIME message\r\n';
+      '  boundary="' +
+      r.boundary +
+      '"\r\n' +
+      "X-Enigmail-Info: Fixed broken PGP/MIME message\r\n";
 
     return r;
   },
 
-
   /**
    * Get corrected body for MS-Exchange messages
    */
-  getCorrectedExchangeBodyData: function(bodyData, boundary) {
-    EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectedExchangeBodyData: boundary='" + boundary + "'\n");
+  getCorrectedExchangeBodyData(bodyData, boundary) {
+    EnigmailLog.DEBUG(
+      "fixExchangeMsg.jsm: getCorrectedExchangeBodyData: boundary='" +
+        boundary +
+        "'\n"
+    );
     let boundRx = new RegExp("^--" + boundary, "gm");
     let match = boundRx.exec(bodyData);
 
     if (match.index < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectedExchangeBodyData: did not find index of mime type to skip\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectedExchangeBodyData: did not find index of mime type to skip\n"
+      );
       return null;
     }
 
     let skipStart = match.index;
     // found first instance -- that's the message part to ignore
     match = boundRx.exec(bodyData);
     if (match.index <= 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectedExchangeBodyData: did not find boundary of PGP/MIME version identification\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectedExchangeBodyData: did not find boundary of PGP/MIME version identification\n"
+      );
       return null;
     }
 
     let versionIdent = match.index;
 
-    if (bodyData.substring(skipStart, versionIdent).search(/^content-type:[ \t]*text\/(plain|html)/mi) < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectedExchangeBodyData: first MIME part is not content-type text/plain or text/html\n");
+    if (
+      bodyData
+        .substring(skipStart, versionIdent)
+        .search(/^content-type:[ \t]*text\/(plain|html)/im) < 0
+    ) {
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectedExchangeBodyData: first MIME part is not content-type text/plain or text/html\n"
+      );
       return null;
     }
 
     match = boundRx.exec(bodyData);
     if (match.index < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectedExchangeBodyData: did not find boundary of PGP/MIME encrypted data\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectedExchangeBodyData: did not find boundary of PGP/MIME encrypted data\n"
+      );
       return null;
     }
 
     let encData = match.index;
-    let mimeHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let mimeHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     mimeHdr.initialize(bodyData.substring(versionIdent, encData));
     let ct = mimeHdr.extractHeader("content-type", false);
 
     if (!ct || ct.search(/application\/pgp-encrypted/i) < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectedExchangeBodyData: wrong content-type of version-identification\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectedExchangeBodyData: wrong content-type of version-identification\n"
+      );
       EnigmailLog.DEBUG("   ct = '" + ct + "'\n");
       return null;
     }
 
     mimeHdr.initialize(bodyData.substr(encData, 5000));
     ct = mimeHdr.extractHeader("content-type", false);
     if (!ct || ct.search(/application\/octet-stream/i) < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectedExchangeBodyData: wrong content-type of PGP/MIME data\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectedExchangeBodyData: wrong content-type of PGP/MIME data\n"
+      );
       EnigmailLog.DEBUG("   ct = '" + ct + "'\n");
       return null;
     }
 
     return bodyData.substr(versionIdent);
   },
 
-
   /**
    * Get corrected body for iPGMail messages
    */
-  getCorrectediPGMailBodyData: function(bodyData, boundary) {
-    EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectediPGMailBodyData: boundary='" + boundary + "'\n");
+  getCorrectediPGMailBodyData(bodyData, boundary) {
+    EnigmailLog.DEBUG(
+      "fixExchangeMsg.jsm: getCorrectediPGMailBodyData: boundary='" +
+        boundary +
+        "'\n"
+    );
     let boundRx = new RegExp("^--" + boundary, "gm");
     let match = boundRx.exec(bodyData);
 
     if (match.index < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectediPGMailBodyData: did not find index of mime type to skip\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectediPGMailBodyData: did not find index of mime type to skip\n"
+      );
       return null;
     }
 
-    let skipStart = match.index;
     // found first instance -- that's the message part to ignore
     match = boundRx.exec(bodyData);
     if (match.index <= 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectediPGMailBodyData: did not find boundary of text/plain msg part\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectediPGMailBodyData: did not find boundary of text/plain msg part\n"
+      );
       return null;
     }
 
     let encData = match.index;
 
     match = boundRx.exec(bodyData);
     if (match.index < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectediPGMailBodyData: did not find end boundary of PGP/MIME encrypted data\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectediPGMailBodyData: did not find end boundary of PGP/MIME encrypted data\n"
+      );
       return null;
     }
 
-    let mimeHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let mimeHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
 
     mimeHdr.initialize(bodyData.substr(encData, 5000));
     let ct = mimeHdr.extractHeader("content-type", false);
     if (!ct || ct.search(/application\/pgp-encrypted/i) < 0) {
-      EnigmailLog.DEBUG("fixExchangeMsg.jsm: getCorrectediPGMailBodyData: wrong content-type of PGP/MIME data\n");
+      EnigmailLog.DEBUG(
+        "fixExchangeMsg.jsm: getCorrectediPGMailBodyData: wrong content-type of PGP/MIME data\n"
+      );
       EnigmailLog.DEBUG("   ct = '" + ct + "'\n");
       return null;
     }
 
-    return "--" + boundary + "\r\n" +
+    return (
+      "--" +
+      boundary +
+      "\r\n" +
       "Content-Type: application/pgp-encrypted\r\n" +
       "Content-Description: PGP/MIME version identification\r\n\r\n" +
       "Version: 1\r\n\r\n" +
-      bodyData.substring(encData, match.index).replace(/^Content-Type: +application\/pgp-encrypted/im,
-        "Content-Type: application/octet-stream") +
-      "--" + boundary + "--\r\n";
+      bodyData
+        .substring(encData, match.index)
+        .replace(
+          /^Content-Type: +application\/pgp-encrypted/im,
+          "Content-Type: application/octet-stream"
+        ) +
+      "--" +
+      boundary +
+      "--\r\n"
+    );
   },
 
-  checkMessageStructure: function(msgData) {
+  checkMessageStructure(msgData) {
     let msgTree = EnigmailMime.getMimeTree(msgData, true);
 
     try {
-
       // check message structure
       let ok =
-        msgTree.headers.get("content-type").type.toLowerCase() === "multipart/encrypted" &&
-        msgTree.headers.get("content-type").get("protocol").toLowerCase() === "application/pgp-encrypted" &&
+        msgTree.headers.get("content-type").type.toLowerCase() ===
+          "multipart/encrypted" &&
+        msgTree.headers
+          .get("content-type")
+          .get("protocol")
+          .toLowerCase() === "application/pgp-encrypted" &&
         msgTree.subParts.length === 2 &&
-        msgTree.subParts[0].headers.get("content-type").type.toLowerCase() === "application/pgp-encrypted" &&
-        msgTree.subParts[1].headers.get("content-type").type.toLowerCase() === "application/octet-stream";
-
+        msgTree.subParts[0].headers.get("content-type").type.toLowerCase() ===
+          "application/pgp-encrypted" &&
+        msgTree.subParts[1].headers.get("content-type").type.toLowerCase() ===
+          "application/octet-stream";
 
       if (ok) {
         // check for existence of PGP Armor
         let body = msgTree.subParts[1].body;
         let p0 = body.search(/^-----BEGIN PGP MESSAGE-----$/m);
         let p1 = body.search(/^-----END PGP MESSAGE-----$/m);
 
-        ok = (p0 >= 0 && p1 > p0 + 32);
+        ok = p0 >= 0 && p1 > p0 + 32;
       }
       return ok;
     } catch (x) {}
     return false;
   },
 
-  copyToTargetFolder: function(msgData) {
+  copyToTargetFolder(msgData) {
     var self = this;
-    var tempFile = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
+    let tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile);
     tempFile.append("message.eml");
     tempFile.createUnique(0, 0o600);
 
     // ensure that file gets deleted on exit, if something goes wrong ...
-    var extAppLauncher = Cc["@mozilla.org/mime;1"].getService(Ci.nsPIExternalAppLauncher);
+    var extAppLauncher = Cc["@mozilla.org/mime;1"].getService(
+      Ci.nsPIExternalAppLauncher
+    );
 
-    var foStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
+    var foStream = Cc[
+      "@mozilla.org/network/file-output-stream;1"
+    ].createInstance(Ci.nsIFileOutputStream);
     foStream.init(tempFile, 2, 0x200, false); // open as "write only"
     foStream.write(msgData, msgData.length);
     foStream.close();
 
     extAppLauncher.deleteTemporaryFileOnExit(tempFile);
 
     // note: nsIMsgFolder.copyFileMessage seems to have a bug on Windows, when
     // the nsIFile has been already used by foStream (because of Windows lock system?), so we
     // must initialize another nsIFile object, pointing to the temporary file
     var fileSpec = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
     fileSpec.initWithPath(tempFile.path);
 
-
     var copyListener = {
-      QueryInterface: function(iid) {
-        if (iid.equals(Ci.nsIMsgCopyServiceListener) || iid.equals(Ci.nsISupports)) {
-          return this;
-        }
-        throw Components.results.NS_NOINTERFACE;
-      },
+      QueryInterface: ChromeUtils.generateQI(["nsIMsgCopyServiceListener"]),
       msgKey: null,
-      GetMessageId: function(messageId) {},
-      OnProgress: function(progress, progressMax) {},
-      OnStartCopy: function() {},
-      SetMessageKey: function(key) {
+      GetMessageId(messageId) {},
+      OnProgress(progress, progressMax) {},
+      OnStartCopy() {},
+      SetMessageKey(key) {
         this.msgKey = key;
       },
-      OnStopCopy: function(statusCode) {
+      OnStopCopy(statusCode) {
         if (statusCode !== 0) {
-          EnigmailLog.DEBUG("fixExchangeMsg.jsm: error copying message: " + statusCode + "\n");
+          EnigmailLog.DEBUG(
+            "fixExchangeMsg.jsm: error copying message: " + statusCode + "\n"
+          );
           try {
             tempFile.remove(false);
           } catch (ex) {
-            EnigmailLog.DEBUG("persistentCrypto.jsm: Could not delete temp file\n");
+            EnigmailLog.DEBUG(
+              "persistentCrypto.jsm: Could not delete temp file\n"
+            );
           }
           self.reject(3);
           return;
         }
         EnigmailLog.DEBUG("fixExchangeMsg.jsm: copy complete\n");
 
-        EnigmailLog.DEBUG("fixExchangeMsg.jsm: deleting message key=" + self.hdr.messageKey + "\n");
-        let msgArray = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
-        msgArray.appendElement(self.hdr, false);
+        EnigmailLog.DEBUG(
+          "fixExchangeMsg.jsm: deleting message key=" +
+            self.hdr.messageKey +
+            "\n"
+        );
+        let msgArray = Cc["@mozilla.org/array;1"].createInstance(
+          Ci.nsIMutableArray
+        );
+        msgArray.appendElement(self.hdr);
 
-        self.hdr.folder.deleteMessages(msgArray, null, true, false, null, false);
+        self.hdr.folder.deleteMessages(
+          msgArray,
+          null,
+          true,
+          false,
+          null,
+          false
+        );
         EnigmailLog.DEBUG("fixExchangeMsg.jsm: deleted original message\n");
 
         try {
           tempFile.remove(false);
         } catch (ex) {
-          EnigmailLog.DEBUG("persistentCrypto.jsm: Could not delete temp file\n");
+          EnigmailLog.DEBUG(
+            "persistentCrypto.jsm: Could not delete temp file\n"
+          );
         }
         self.resolve(this.msgKey);
-        return;
-      }
+      },
     };
 
-    EnigmailCompat.copyFileToMailFolder(fileSpec, this.destFolder, 0, this.hdr.flags, copyListener, null);
-  }
+    EnigmailCompat.copyFileToMailFolder(
+      fileSpec,
+      this.destFolder,
+      0,
+      this.hdr.flags,
+      copyListener,
+      null
+    );
+  },
 };
--- a/mail/extensions/openpgp/content/modules/funcs.jsm
+++ b/mail/extensions/openpgp/content/modules/funcs.jsm
@@ -1,139 +1,161 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailFuncs"];
 
 /*
  * Common Enigmail crypto-related GUI functionality
  *
  */
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
 
 var gTxtConverter = null;
 
 var EnigmailFuncs = {
   /**
    * get a list of plain email addresses without name or surrounding <>
    * @param mailAddrs |string| - address-list encdoded in Unicode as specified in RFC 2822, 3.4
    *                             separated by , or ;
    *
    * @return |string|          - list of pure email addresses separated by ","
    */
-  stripEmail: function(mailAddresses) {
+  stripEmail(mailAddresses) {
     // EnigmailLog.DEBUG("funcs.jsm: stripEmail(): mailAddresses=" + mailAddresses + "\n");
 
     const SIMPLE = "[^<>,]+"; // RegExp for a simple email address (e.g. a@b.c)
     const COMPLEX = "[^<>,]*<[^<>, ]+>"; // RegExp for an address containing <...> (e.g. Name <a@b.c>)
-    const MatchAddr = new RegExp("^(" + SIMPLE + "|" + COMPLEX + ")(," + SIMPLE + "|," + COMPLEX + ")*$");
+    const MatchAddr = new RegExp(
+      "^(" + SIMPLE + "|" + COMPLEX + ")(," + SIMPLE + "|," + COMPLEX + ")*$"
+    );
 
     let mailAddrs = mailAddresses;
 
     let qStart, qEnd;
     while ((qStart = mailAddrs.indexOf('"')) >= 0) {
       qEnd = mailAddrs.indexOf('"', qStart + 1);
       if (qEnd < 0) {
-        EnigmailLog.ERROR("funcs.jsm: stripEmail: Unmatched quote in mail address: '" + mailAddresses + "'\n");
-        throw Components.results.NS_ERROR_FAILURE;
+        EnigmailLog.ERROR(
+          "funcs.jsm: stripEmail: Unmatched quote in mail address: '" +
+            mailAddresses +
+            "'\n"
+        );
+        throw Cr.NS_ERROR_FAILURE;
       }
 
-      mailAddrs = mailAddrs.substring(0, qStart) + mailAddrs.substring(qEnd + 1);
+      mailAddrs =
+        mailAddrs.substring(0, qStart) + mailAddrs.substring(qEnd + 1);
     }
 
     // replace any ";" by ","; remove leading/trailing ","
-    mailAddrs = mailAddrs.replace(/[,;]+/g, ",").replace(/^,/, "").replace(/,$/, "");
+    mailAddrs = mailAddrs
+      .replace(/[,;]+/g, ",")
+      .replace(/^,/, "")
+      .replace(/,$/, "");
 
-    if (mailAddrs.length === 0) return "";
+    if (mailAddrs.length === 0) {
+      return "";
+    }
 
     // having two <..> <..> in one email, or things like <a@b.c,><d@e.f> is an error
     if (mailAddrs.search(MatchAddr) < 0) {
-      EnigmailLog.ERROR("funcs.jsm: stripEmail: Invalid <..> brackets in mail address: '" + mailAddresses + "'\n");
-      throw Components.results.NS_ERROR_FAILURE;
+      EnigmailLog.ERROR(
+        "funcs.jsm: stripEmail: Invalid <..> brackets in mail address: '" +
+          mailAddresses +
+          "'\n"
+      );
+      throw Cr.NS_ERROR_FAILURE;
     }
 
     // We know that the "," and the < > are at the right places, thus we can split by ","
     let addrList = mailAddrs.split(/,/);
 
     for (let i in addrList) {
       // Extract pure e-mail address list (strip out anything before angle brackets and any whitespace)
-      addrList[i] = addrList[i].replace(/^([^<>]*<)([^<>]+)(>)$/, "$2").replace(/\s/g, "");
+      addrList[i] = addrList[i]
+        .replace(/^([^<>]*<)([^<>]+)(>)$/, "$2")
+        .replace(/\s/g, "");
     }
 
     // remove repeated, trailing and leading "," (again, as there may be empty addresses)
-    mailAddrs = addrList.join(",").replace(/,,/g, ",").replace(/^,/, "").replace(/,$/, "");
+    mailAddrs = addrList
+      .join(",")
+      .replace(/,,/g, ",")
+      .replace(/^,/, "")
+      .replace(/,$/, "");
 
     return mailAddrs;
   },
 
   /**
    * get an array of email object (email, name) from an address string
    * @param mailAddrs |string| - address-list as specified in RFC 2822, 3.4
    *                             separated by ","; encoded according to RFC 2047
    *
    * @return |array| of msgIAddressObject
    */
-  parseEmails: function(mailAddrs, encoded = true) {
-
+  parseEmails(mailAddrs, encoded = true) {
     try {
-      let hdr = Cc["@mozilla.org/messenger/headerparser;1"].createInstance(Ci.nsIMsgHeaderParser);
+      let hdr = Cc["@mozilla.org/messenger/headerparser;1"].createInstance(
+        Ci.nsIMsgHeaderParser
+      );
       if (encoded) {
         return hdr.parseEncodedHeader(mailAddrs, "utf-8");
       }
       return hdr.parseDecodedHeader(mailAddrs);
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     return [];
   },
 
   /**
    * Hide all menu entries and other XUL elements that are considered for
    * advanced users. The XUL items must contain 'advanced="true"' or
    * 'advanced="reverse"'.
    *
    * @obj:       |object| - XUL tree element
    * @attribute: |string| - attribute to set or remove (i.e. "hidden" or "collapsed")
    * @dummy:     |object| - anything
    *
    * no return value
    */
 
-
-  collapseAdvanced: function(obj, attribute, dummy) {
+  collapseAdvanced(obj, attribute, dummy) {
     EnigmailLog.DEBUG("funcs.jsm: collapseAdvanced:\n");
 
     var advancedUser = EnigmailPrefs.getPref("advancedUser");
 
     obj = obj.firstChild;
     while (obj) {
       if ("getAttribute" in obj) {
         if (obj.getAttribute("advanced") == "true") {
           if (advancedUser) {
             obj.removeAttribute(attribute);
-          }
-          else {
+          } else {
             obj.setAttribute(attribute, "true");
           }
-        }
-        else if (obj.getAttribute("advanced") == "reverse") {
+        } else if (obj.getAttribute("advanced") == "reverse") {
           if (advancedUser) {
             obj.setAttribute(attribute, "true");
-          }
-          else {
+          } else {
             obj.removeAttribute(attribute);
           }
         }
       }
 
       obj = obj.nextSibling;
     }
   },
@@ -141,19 +163,22 @@ var EnigmailFuncs = {
   /**
    * this function tries to mimic the Thunderbird plaintext viewer
    *
    * @plainTxt - |string| containing the plain text data
    *
    * @ return HTML markup to display mssage
    */
 
-  formatPlaintextMsg: function(plainTxt) {
-    if (!gTxtConverter)
-      gTxtConverter = Cc["@mozilla.org/txttohtmlconv;1"].createInstance(Ci.mozITXTToHTMLConv);
+  formatPlaintextMsg(plainTxt) {
+    if (!gTxtConverter) {
+      gTxtConverter = Cc["@mozilla.org/txttohtmlconv;1"].createInstance(
+        Ci.mozITXTToHTMLConv
+      );
+    }
 
     var prefRoot = EnigmailPrefs.getPrefRoot();
     var fontStyle = "";
 
     // set the style stuff according to perferences
 
     switch (prefRoot.getIntPref("mail.quoted_style")) {
       case 1:
@@ -174,148 +199,171 @@ var EnigmailFuncs = {
       case 2:
         fontStyle += "font-size: small; ";
         break;
     }
 
     fontStyle += "color: " + prefRoot.getCharPref("mail.citation_color") + ";";
 
     var convFlags = Ci.mozITXTToHTMLConv.kURLs;
-    if (prefRoot.getBoolPref("mail.display_glyph"))
+    if (prefRoot.getBoolPref("mail.display_glyph")) {
       convFlags |= Ci.mozITXTToHTMLConv.kGlyphSubstitution;
-    if (prefRoot.getBoolPref("mail.display_struct"))
+    }
+    if (prefRoot.getBoolPref("mail.display_struct")) {
       convFlags |= Ci.mozITXTToHTMLConv.kStructPhrase;
+    }
 
     // start processing the message
 
     plainTxt = plainTxt.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
     var lines = plainTxt.split(/\n/);
     var oldCiteLevel = 0;
     var citeLevel = 0;
     var preface = "";
     var logLineStart = {
-      value: 0
+      value: 0,
     };
     var isSignature = false;
 
     for (var i = 0; i < lines.length; i++) {
       preface = "";
       oldCiteLevel = citeLevel;
-      if (lines[i].search(/^[> \t]*>$/) === 0)
+      if (lines[i].search(/^[> \t]*>$/) === 0) {
         lines[i] += " ";
+      }
 
       citeLevel = gTxtConverter.citeLevelTXT(lines[i], logLineStart);
 
       if (citeLevel > oldCiteLevel) {
-
-        preface = '</pre>';
+        preface = "</pre>";
         for (let j = 0; j < citeLevel - oldCiteLevel; j++) {
           preface += '<blockquote type="cite" style="' + fontStyle + '">';
         }
         preface += '<pre wrap="">\n';
-      }
-      else if (citeLevel < oldCiteLevel) {
-        preface = '</pre>';
-        for (let j = 0; j < oldCiteLevel - citeLevel; j++)
+      } else if (citeLevel < oldCiteLevel) {
+        preface = "</pre>";
+        for (let j = 0; j < oldCiteLevel - citeLevel; j++) {
           preface += "</blockquote>";
+        }
 
         preface += '<pre wrap="">\n';
       }
 
       if (logLineStart.value > 0) {
-        preface += '<span class="moz-txt-citetags">' +
-          gTxtConverter.scanTXT(lines[i].substr(0, logLineStart.value), convFlags) +
-          '</span>';
-      }
-      else if (lines[i] == "-- ") {
+        preface +=
+          '<span class="moz-txt-citetags">' +
+          gTxtConverter.scanTXT(
+            lines[i].substr(0, logLineStart.value),
+            convFlags
+          ) +
+          "</span>";
+      } else if (lines[i] == "-- ") {
         preface += '<div class="moz-txt-sig">';
         isSignature = true;
       }
-      lines[i] = preface + gTxtConverter.scanTXT(lines[i].substr(logLineStart.value), convFlags);
-
+      lines[i] =
+        preface +
+        gTxtConverter.scanTXT(lines[i].substr(logLineStart.value), convFlags);
     }
 
-    var r = '<pre wrap="">' + lines.join("\n") + (isSignature ? '</div>' : '') + '</pre>';
+    var r =
+      '<pre wrap="">' +
+      lines.join("\n") +
+      (isSignature ? "</div>" : "") +
+      "</pre>";
     //EnigmailLog.DEBUG("funcs.jsm: r='"+r+"'\n");
     return r;
   },
 
-
   /**
    * extract the data fields following a header.
    * e.g. ContentType: xyz; Aa=b; cc=d
    * @data: |string| containing a single header
    *
    * @return |array| of |arrays| containing pairs of aa/b and cc/d
    */
-  getHeaderData: function(data) {
-    EnigmailLog.DEBUG("funcs.jsm: getHeaderData: " + data.substr(0, 100) + "\n");
+  getHeaderData(data) {
+    EnigmailLog.DEBUG(
+      "funcs.jsm: getHeaderData: " + data.substr(0, 100) + "\n"
+    );
     var a = data.split(/\n/);
     var res = [];
     for (let i = 0; i < a.length; i++) {
-      if (a[i].length === 0) break;
+      if (a[i].length === 0) {
+        break;
+      }
       let b = a[i].split(/;/);
 
       // extract "abc = xyz" tuples
       for (let j = 0; j < b.length; j++) {
         let m = b[j].match(/^(\s*)([^=\s;]+)(\s*)(=)(\s*)(.*)(\s*)$/);
         if (m) {
           // m[2]: identifier / m[6]: data
           res[m[2].toLowerCase()] = m[6].replace(/\s*$/, "");
-          EnigmailLog.DEBUG("funcs.jsm: getHeaderData: " + m[2].toLowerCase() + " = " + res[m[2].toLowerCase()] + "\n");
+          EnigmailLog.DEBUG(
+            "funcs.jsm: getHeaderData: " +
+              m[2].toLowerCase() +
+              " = " +
+              res[m[2].toLowerCase()] +
+              "\n"
+          );
         }
       }
-      if (i === 0 && a[i].indexOf(";") < 0) break;
-      if (i > 0 && a[i].search(/^\s/) < 0) break;
+      if (i === 0 && !a[i].includes(";")) {
+        break;
+      }
+      if (i > 0 && a[i].search(/^\s/) < 0) {
+        break;
+      }
     }
     return res;
   },
 
   /***
    * Get the text for the encrypted subject (either configured by user or default)
    */
-  getProtectedSubjectText: function() {
+  getProtectedSubjectText() {
     if (EnigmailPrefs.getPref("protectedSubjectText").length > 0) {
-      return EnigmailData.convertToUnicode(EnigmailPrefs.getPref("protectedSubjectText"), "utf-8");
+      return EnigmailData.convertToUnicode(
+        EnigmailPrefs.getPref("protectedSubjectText"),
+        "utf-8"
+      );
     }
-    else {
-      return "...";
-    }
+
+    return "...";
   },
 
-  cloneObj: function(orig) {
+  cloneObj(orig) {
     let newObj;
 
     if (typeof orig !== "object" || orig === null || orig === undefined) {
       return orig;
     }
 
     if ("clone" in orig && typeof orig.clone === "function") {
       return orig.clone();
     }
 
     if (Array.isArray(orig) && orig.length > 0) {
       newObj = [];
       for (let i in orig) {
         if (typeof orig[i] === "object") {
           newObj.push(this.cloneObj(orig[i]));
-        }
-        else {
+        } else {
           newObj.push(orig[i]);
         }
       }
-    }
-    else {
+    } else {
       newObj = {};
       for (let i in orig) {
         if (typeof orig[i] === "object") {
           newObj[i] = this.cloneObj(orig[i]);
+        } else {
+          newObj[i] = orig[i];
         }
-        else
-          newObj[i] = orig[i];
       }
     }
 
     return newObj;
   },
 
   /**
    * Compare two MIME part numbers to determine which of the two is earlier in the tree
@@ -327,58 +375,53 @@ var EnigmailFuncs = {
    *        - Negative number if mime1 is before mime2
    *        - Positive number if mime1 is after mime2
    *        - 0 if mime1 and mime2 are equal
    *        - if mime1 is a parent of mime2 the return value is -2
    *        - if mime2 is a parent of mime1 the return value is 2
    *
    *      Throws an error if mime1 or mime2 do not comply to the required format
    */
-  compareMimePartLevel: function(mime1, mime2) {
+  compareMimePartLevel(mime1, mime2) {
     let s = new RegExp("^[0-9]+(\\.[0-9]+)*$");
-    if (mime1.search(s) < 0) throw new Error("Invalid mime1");
-    if (mime2.search(s) < 0) throw new Error("Invalid mime2");
+    if (mime1.search(s) < 0) {
+      throw new Error("Invalid mime1");
+    }
+    if (mime2.search(s) < 0) {
+      throw new Error("Invalid mime2");
+    }
 
     let a1 = mime1.split(/\./);
     let a2 = mime2.split(/\./);
 
     for (let i = 0; i < Math.min(a1.length, a2.length); i++) {
-      if (Number(a1[i]) < Number(a2[i])) return -1;
-      if (Number(a1[i]) > Number(a2[i])) return 1;
+      if (Number(a1[i]) < Number(a2[i])) {
+        return -1;
+      }
+      if (Number(a1[i]) > Number(a2[i])) {
+        return 1;
+      }
     }
 
-    if (a2.length > a1.length) return -2;
-    if (a2.length < a1.length) return 2;
+    if (a2.length > a1.length) {
+      return -2;
+    }
+    if (a2.length < a1.length) {
+      return 2;
+    }
     return 0;
   },
 
-
-  /**
-   * Determine the total number of certificates in the X.509 certificates store
-   *
-   * @return {Number}: number of Certificates
-   */
-  getNumOfX509Certs: function() {
-
-    let certDb = Cc["@mozilla.org/security/x509certdb;1"].getService(Ci.nsIX509CertDB);
-    let certs = certDb.getCerts();
-    let nCerts = 0;
-
-    if (certs) {
-      let nCerts = [...certs.getEnumerator()].length;
-    }
-
-    return nCerts;
-  },
-
   /**
    * Get the nsIMsgAccount associated with a given nsIMsgIdentity
    */
-  getAccountForIdentity: function(identity) {
-    let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+  getAccountForIdentity(identity) {
+    let accountManager = Cc[
+      "@mozilla.org/messenger/account-manager;1"
+    ].getService(Ci.nsIMsgAccountManager);
 
     for (let acct = 0; acct < accountManager.accounts.length; acct++) {
       let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);
 
       for (let i = 0; i < ac.identities.length; i++) {
         let id = ac.identities.queryElementAt(i, Ci.nsIMsgIdentity);
         if (id.key === identity.key) {
           return ac;
@@ -386,114 +429,103 @@ var EnigmailFuncs = {
       }
     }
     return null;
   },
 
   /**
    * Get the default identity of the default account
    */
-  getDefaultIdentity: function() {
-    let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+  getDefaultIdentity() {
+    let accountManager = Cc[
+      "@mozilla.org/messenger/account-manager;1"
+    ].getService(Ci.nsIMsgAccountManager);
 
     try {
       let ac;
       if (accountManager.defaultAccount) {
         ac = accountManager.defaultAccount;
-      }
-      else {
+      } else {
         for (let i = 0; i < accountManager.accounts.length; i++) {
           ac = accountManager.accounts.queryElementAt(i, Ci.nsIMsgAccount);
-          if (ac.incomingServer.type === "imap" || ac.incomingServer.type === "pop3") break;
+          if (
+            ac.incomingServer.type === "imap" ||
+            ac.incomingServer.type === "pop3"
+          ) {
+            break;
+          }
         }
       }
 
       if (ac.defaultIdentity) {
         return ac.defaultIdentity;
       }
       return ac.identities.queryElementAt(0, Ci.nsIMsgIdentity);
-    }
-    catch (x) {
+    } catch (x) {
       return null;
     }
   },
 
   /**
    * Strip extended email parts such as "+xyz" from "abc+xyz@gmail.com" for known domains
    * Currently supported domains: gmail.com, googlemail.com
    */
-  getBaseEmail: function(emailAddr) {
+  getBaseEmail(emailAddr) {
     return emailAddr.replace(/\+.{1,999}@(gmail|googlemail).com$/i, "");
   },
 
   /**
    * Get a list of all own email addresses, taken from all identities
    * and all reply-to addresses
    */
-  getOwnEmailAddresses: function() {
+  getOwnEmailAddresses() {
     let ownEmails = {};
 
-    let am = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+    let am = Cc["@mozilla.org/messenger/account-manager;1"].getService(
+      Ci.nsIMsgAccountManager
+    );
 
     // Determine all sorts of own email addresses
     for (let i = 0; i < am.allIdentities.length; i++) {
       let id = am.allIdentities.queryElementAt(i, Ci.nsIMsgIdentity);
-      if (id.email && id.email.length > 0) ownEmails[this.getBaseEmail(id.email.toLowerCase())] = 1;
+      if (id.email && id.email.length > 0) {
+        ownEmails[this.getBaseEmail(id.email.toLowerCase())] = 1;
+      }
       if (id.replyTo && id.replyTo.length > 0) {
         try {
-          let replyEmails = this.stripEmail(id.replyTo).toLowerCase().split(/,/);
+          let replyEmails = this.stripEmail(id.replyTo)
+            .toLowerCase()
+            .split(/,/);
           for (let j in replyEmails) {
             ownEmails[this.getBaseEmail(replyEmails[j])] = 1;
           }
-        }
-        catch (ex) {}
+        } catch (ex) {}
       }
     }
 
     return ownEmails;
   },
 
   /**
    * Determine the distinct number of non-self recipients of a message.
    * Only To: and Cc: fields are considered.
    */
-  getNumberOfRecipients: function(msgCompField) {
+  getNumberOfRecipients(msgCompField) {
     let recipients = {},
       ownEmails = this.getOwnEmailAddresses();
 
-    let allAddr = (this.stripEmail(msgCompField.to) + "," + this.stripEmail(msgCompField.cc)).toLowerCase();
+    let allAddr = (
+      this.stripEmail(msgCompField.to) +
+      "," +
+      this.stripEmail(msgCompField.cc)
+    ).toLowerCase();
     let emails = allAddr.split(/,+/);
 
     for (let i = 0; i < emails.length; i++) {
       let r = this.getBaseEmail(emails[i]);
       if (r.length > 0 && !(r in ownEmails)) {
         recipients[r] = 1;
       }
     }
 
-    let numRecipients = 0;
-    for (let i in recipients) {
-      ++numRecipients;
-    }
-
-    return numRecipients;
+    return recipients.length;
   },
-
-  /**
-   * Synchronize a promise
-   */
-  syncPromise: function(promise) {
-    let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
-
-    let res = null;
-    let p = promise.then(gotResult => {
-      res = gotResult;
-      inspector.exitNestedEventLoop();
-    }).catch(gotResult => {
-      res = gotResult;
-      inspector.exitNestedEventLoop();
-    });
-
-    inspector.enterNestedEventLoop(0);
-
-    return res;
-  }
 };
--- a/mail/extensions/openpgp/content/modules/glodaUtils.jsm
+++ b/mail/extensions/openpgp/content/modules/glodaUtils.jsm
@@ -12,17 +12,18 @@
 "use strict";
 
 var EXPORTED_SYMBOLS = ["GlodaUtils"];
 
 var GlodaUtils = null;
 
 try {
   // TB with omnijar
-  GlodaUtils = ChromeUtils.import("resource:///modules/gloda/GlodaUtils.jsm").GlodaUtils;
-}
-catch (ex) {
+  GlodaUtils = ChromeUtils.import("resource:///modules/gloda/GlodaUtils.jsm")
+    .GlodaUtils;
+} catch (ex) {
   // "old style" TB
-  GlodaUtils = ChromeUtils.import("resource://app/modules/gloda/GlodaUtils.jsm").GlodaUtils;
+  GlodaUtils = ChromeUtils.import("resource://app/modules/gloda/GlodaUtils.jsm")
+    .GlodaUtils;
 }
 
 // We don't define the exported symbol here - that is on purpose
 // The goal of this module is simply to simplify loading of the component
--- a/mail/extensions/openpgp/content/modules/gpg.jsm
+++ b/mail/extensions/openpgp/content/modules/gpg.jsm
@@ -1,69 +1,43 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailGpg"];
 
-
-
-
-
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-const EnigmailVersioning = ChromeUtils.import("chrome://openpgp/content/modules/versioning.jsm").EnigmailVersioning;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const getDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailVersioning = ChromeUtils.import(
+  "chrome://openpgp/content/modules/versioning.jsm"
+).EnigmailVersioning;
 
 const MINIMUM_GPG_VERSION = "2.0.14";
-const GPG_BATCH_OPT_LIST = ["--batch", "--no-tty", "--no-verbose", "--status-fd", "2"];
-
-function pushTrimmedStr(arr, str, splitStr) {
-  // Helper function for pushing a string without leading/trailing spaces
-  // to an array
-  str = str.replace(/^ */, "").replace(/ *$/, "");
-  if (str.length > 0) {
-    if (splitStr) {
-      const tmpArr = str.split(/[\t ]+/);
-      for (let i = 0; i < tmpArr.length; i++) {
-        arr.push(tmpArr[i]);
-      }
-    } else {
-      arr.push(str);
-    }
-  }
-  return (str.length > 0);
-}
 
 var EnigmailGpg = {
   agentVersion: "",
   _agentPath: null,
 
   get agentPath() {
     return this._agentPath;
   },
 
-  setAgentPath: function(path) {
+  setAgentPath(path) {
     this._agentPath = path;
   },
 
   /**
    * return the minimum version of GnuPG that is supported by Enigmail
    */
-  getMinimumGpgVersion: function() {
+  getMinimumGpgVersion() {
     return MINIMUM_GPG_VERSION;
   },
 
   /***
    determine if a specific feature is available in the GnuPG version used
 
    @param featureName:  String; one of the following values:
    version-supported    - is the gpg version supported at all (true for gpg >= 2.0.10)
@@ -81,50 +55,60 @@ var EnigmailGpg = {
    export-specific-uid  - does gpg support exporting a key with a specific UID (true for gpg >= 2.2.8)
    supports-show-only   - does gpg support --import-options show-only (true for gpg >= 2.1.14)
    handles-huge-keys    - can gpg deal with huge keys without aborting (true for gpg >= 2.2.17)
 
    @return: depending on featureName - Boolean unless specified differently:
    (true if feature is available / false otherwise)
    If the feature cannot be found, undefined is returned
    */
-  getGpgFeature: function(featureName) {
+  getGpgFeature(featureName) {
     let gpgVersion = EnigmailGpg.agentVersion;
 
-    if (!gpgVersion || typeof(gpgVersion) != "string" || gpgVersion.length === 0) {
+    if (
+      !gpgVersion ||
+      typeof gpgVersion != "string" ||
+      gpgVersion.length === 0
+    ) {
       return undefined;
     }
 
     gpgVersion = gpgVersion.replace(/-.*$/, "");
     if (gpgVersion.search(/^\d+\.\d+/) < 0) {
       // not a valid version number
       return undefined;
     }
 
     switch (featureName) {
       case "version-supported":
-        return EnigmailVersioning.greaterThanOrEqual(gpgVersion, MINIMUM_GPG_VERSION);
+        return EnigmailVersioning.greaterThanOrEqual(
+          gpgVersion,
+          MINIMUM_GPG_VERSION
+        );
       case "supports-gpg-agent":
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.0.16");
       case "keygen-passphrase":
-        return EnigmailVersioning.lessThan(gpgVersion, "2.1") || EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.1.2");
+        return (
+          EnigmailVersioning.lessThan(gpgVersion, "2.1") ||
+          EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.1.2")
+        );
       case "genkey-no-protection":
         return EnigmailVersioning.greaterThan(gpgVersion, "2.1");
       case "windows-photoid-bug":
         return EnigmailVersioning.lessThan(gpgVersion, "2.0.16");
       case "supports-ecc-keys":
         return EnigmailVersioning.greaterThan(gpgVersion, "2.1");
       case "socks-on-windows":
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.0.20");
       case "search-keys-cmd":
         // returns a string
         if (EnigmailVersioning.greaterThan(gpgVersion, "2.1")) {
           return "save";
-        } else
-          return "quit";
+        }
+        return "quit";
       case "supports-sender":
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.1.15");
       case "export-result":
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.1.10");
       case "decryption-info":
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.0.19");
       case "supports-wkd":
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.1.19");
@@ -134,17 +118,17 @@ var EnigmailGpg = {
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.1.14");
       case "handles-huge-keys":
         return EnigmailVersioning.greaterThanOrEqual(gpgVersion, "2.2.17");
     }
 
     return undefined;
   },
 
-  signingAlgIdToString: function(id) {
+  signingAlgIdToString(id) {
     // RFC 4880 Sec. 9.1, RFC 6637 Sec. 5 and draft-koch-eddsa-for-openpgp-03 Sec. 8
     switch (parseInt(id, 10)) {
       case 1:
       case 2:
       case 3:
         return "RSA";
       case 16:
         return "Elgamal";
@@ -154,21 +138,23 @@ var EnigmailGpg = {
         return "ECDH";
       case 19:
         return "ECDSA";
       case 20:
         return "ELG";
       case 22:
         return "EDDSA";
       default:
-        return EnigmailLocale.getString("unknownSigningAlg", [parseInt(id, 10)]);
+        return EnigmailLocale.getString("unknownSigningAlg", [
+          parseInt(id, 10),
+        ]);
     }
   },
 
-  hashAlgIdToString: function(id) {
+  hashAlgIdToString(id) {
     // RFC 4880 Sec. 9.4
     switch (parseInt(id, 10)) {
       case 1:
         return "MD5";
       case 2:
         return "SHA-1";
       case 3:
         return "RIPE-MD/160";
--- a/mail/extensions/openpgp/content/modules/hash.jsm
+++ b/mail/extensions/openpgp/content/modules/hash.jsm
@@ -1,125 +1,172 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailHash"];
 
-
-
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailEncryption = ChromeUtils.import("chrome://openpgp/content/modules/encryption.jsm").EnigmailEncryption;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-
-
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailEncryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/encryption.jsm"
+).EnigmailEncryption;
+const EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
 
 const keyAlgorithms = [];
-const mimeHashAlgorithms = [null, "sha1", "ripemd160", "sha256", "sha384", "sha512", "sha224", "md5"];
+const mimeHashAlgorithms = [
+  null,
+  "sha1",
+  "ripemd160",
+  "sha256",
+  "sha384",
+  "sha512",
+  "sha224",
+  "md5",
+];
 
 var EnigmailHash = {
-  determineAlgorithm: function(win, uiFlags, fromMailAddr, hashAlgoObj) {
+  determineAlgorithm(win, uiFlags, fromMailAddr, hashAlgoObj) {
     EnigmailLog.DEBUG("hash.jsm: determineAlgorithm\n");
 
     if (!win) {
       win = EnigmailWindows.getMostRecentWindow();
     }
 
-    const sendFlags = EnigmailConstants.SEND_TEST | EnigmailConstants.SEND_SIGNED;
-    const hashAlgo = mimeHashAlgorithms[EnigmailPrefs.getPref("mimeHashAlgorithm")];
+    const sendFlags =
+      EnigmailConstants.SEND_TEST | EnigmailConstants.SEND_SIGNED;
+    const hashAlgo =
+      mimeHashAlgorithms[EnigmailPrefs.getPref("mimeHashAlgorithm")];
 
-    if (typeof(keyAlgorithms[fromMailAddr]) != "string") {
+    if (typeof keyAlgorithms[fromMailAddr] != "string") {
       // hash algorithm not yet known
 
       const testUiFlags = EnigmailConstants.UI_TEST;
       const listener = {
         stdoutData: "",
         stderrData: "",
         exitCode: -1,
-        stdin: function(pipe) {
+        stdin(pipe) {
           pipe.write("Dummy Test");
           pipe.close();
         },
-        stdout: function(data) {
+        stdout(data) {
           this.stdoutData += data;
         },
-        stderr: function(data) {
+        stderr(data) {
           this.stderrData += data;
         },
-        done: function(exitCode) {
+        done(exitCode) {
           this.exitCode = exitCode;
-        }
+        },
       };
 
       let errorMsgObj = {};
       let statusFlagsObj = {};
-      const proc = EnigmailEncryption.encryptMessageStart(win, testUiFlags, fromMailAddr, "",
-        "", hashAlgo, sendFlags,
-        listener, statusFlagsObj, errorMsgObj);
+      const proc = EnigmailEncryption.encryptMessageStart(
+        win,
+        testUiFlags,
+        fromMailAddr,
+        "",
+        "",
+        hashAlgo,
+        sendFlags,
+        listener,
+        statusFlagsObj,
+        errorMsgObj
+      );
 
       if (!proc) {
         hashAlgoObj.errorMsg = errorMsgObj.value;
         hashAlgoObj.statusFlags = statusFlagsObj.value;
         return 1;
       }
 
       proc.wait();
 
       const msgText = listener.stdoutData;
       const exitCode = listener.exitCode;
 
       const retStatusObj = {};
-      let exitCode2 = EnigmailEncryption.encryptMessageEnd(fromMailAddr, listener.stderrData, exitCode,
-        testUiFlags, sendFlags, 10,
-        retStatusObj);
+      let exitCode2 = EnigmailEncryption.encryptMessageEnd(
+        fromMailAddr,
+        listener.stderrData,
+        exitCode,
+        testUiFlags,
+        sendFlags,
+        10,
+        retStatusObj
+      );
 
-      if ((exitCode2 === 0) && !msgText) exitCode2 = 1;
+      if (exitCode2 === 0 && !msgText) {
+        exitCode2 = 1;
+      }
       // if (exitCode2 > 0) exitCode2 = -exitCode2;
 
       if (exitCode2 !== 0) {
         // Abormal return
         if (retStatusObj.statusFlags & EnigmailConstants.BAD_PASSPHRASE) {
           // "Unremember" passphrase on error return
           retStatusObj.errorMsg = EnigmailLocale.getString("badPhrase");
         }
         EnigmailDialog.alert(win, retStatusObj.errorMsg);
         return exitCode2;
       }
 
       let hashAlgorithm = "sha1"; // default as defined in RFC 4880, section 7 is MD5 -- but that's outdated
 
       const m = msgText.match(/^(Hash: )(.*)$/m);
-      if (m && (m.length > 2) && (m[1] == "Hash: ")) {
+      if (m && m.length > 2 && m[1] == "Hash: ") {
         hashAlgorithm = m[2].toLowerCase();
-      }
-      else {
-        EnigmailLog.DEBUG("hash.jsm: determineAlgorithm: no hashAlgorithm specified - using MD5\n");
+      } else {
+        EnigmailLog.DEBUG(
+          "hash.jsm: determineAlgorithm: no hashAlgorithm specified - using MD5\n"
+        );
       }
 
       for (let i = 1; i < mimeHashAlgorithms.length; i++) {
         if (mimeHashAlgorithms[i] === hashAlgorithm) {
-          EnigmailLog.DEBUG("hash.jsm: determineAlgorithm: found hashAlgorithm " + hashAlgorithm + "\n");
+          EnigmailLog.DEBUG(
+            "hash.jsm: determineAlgorithm: found hashAlgorithm " +
+              hashAlgorithm +
+              "\n"
+          );
           keyAlgorithms[fromMailAddr] = hashAlgorithm;
           hashAlgoObj.value = hashAlgorithm;
           return 0;
         }
       }
 
-      EnigmailLog.ERROR("hash.jsm: determineAlgorithm: no hashAlgorithm found\n");
+      EnigmailLog.ERROR(
+        "hash.jsm: determineAlgorithm: no hashAlgorithm found\n"
+      );
       return 2;
     }
-    else {
-      EnigmailLog.DEBUG("hash.jsm: determineAlgorithm: hashAlgorithm " + keyAlgorithms[fromMailAddr] + " is cached\n");
-      hashAlgoObj.value = keyAlgorithms[fromMailAddr];
-    }
+
+    EnigmailLog.DEBUG(
+      "hash.jsm: determineAlgorithm: hashAlgorithm " +
+        keyAlgorithms[fromMailAddr] +
+        " is cached\n"
+    );
+    hashAlgoObj.value = keyAlgorithms[fromMailAddr];
 
     return 0;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/httpProxy.jsm
+++ b/mail/extensions/openpgp/content/modules/httpProxy.jsm
@@ -3,26 +3,25 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailHttpProxy"];
 
-
-
-
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-
-const NS_PREFS_SERVICE_CID = "@mozilla.org/preferences-service;1";
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
 
 function getPasswdForHost(hostname, userObj, passwdObj) {
-  var loginmgr = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
+  var loginmgr = Services.logins;
 
   // search HTTP password 1st
   var logins = loginmgr.findLogins({}, "http://" + hostname, "", "");
   if (logins.length > 0) {
     userObj.value = logins[0].username;
     passwdObj.value = logins[0].password;
     return true;
   }
@@ -43,43 +42,52 @@ var EnigmailHttpProxy = {
   /**
    *  get Proxy for a given hostname as configured in Mozilla
    *
    *  @hostname: String - the host to check if there is a proxy.
    *
    *  @return: String - proxy host URL to provide to GnuPG
    *                    null if no proxy required
    */
-  getHttpProxy: function(hostName) {
+  getHttpProxy(hostName) {
     var proxyHost = null;
-    if (((typeof hostName) !== 'undefined') && EnigmailPrefs.getPref("respectHttpProxy")) {
+    if (
+      typeof hostName !== "undefined" &&
+      EnigmailPrefs.getPref("respectHttpProxy")
+    ) {
       // determine proxy host
-      var prefsSvc = Cc[NS_PREFS_SERVICE_CID].getService(Ci.nsIPrefService);
+      var prefsSvc = Services.prefs;
       var prefRoot = prefsSvc.getBranch(null);
       var useProxy = prefRoot.getIntPref("network.proxy.type");
       if (useProxy == 1) {
         var proxyHostName = prefRoot.getCharPref("network.proxy.http");
         var proxyHostPort = prefRoot.getIntPref("network.proxy.http_port");
-        var noProxy = prefRoot.getCharPref("network.proxy.no_proxies_on").split(/[ ,]/);
+        var noProxy = prefRoot
+          .getCharPref("network.proxy.no_proxies_on")
+          .split(/[ ,]/);
         for (var i = 0; i < noProxy.length; i++) {
-          var proxySearch = new RegExp(noProxy[i].replace(/\./g, "\\.").replace(/\*/g, ".*") + "$", "i");
+          var proxySearch = new RegExp(
+            noProxy[i].replace(/\./g, "\\.").replace(/\*/g, ".*") + "$",
+            "i"
+          );
           if (noProxy[i] && hostName.search(proxySearch) >= 0) {
             i = noProxy.length + 1;
             proxyHostName = null;
           }
         }
 
         if (proxyHostName) {
           var userObj = {};
           var passwdObj = {};
           if (getPasswdForHost(proxyHostName, userObj, passwdObj)) {
-            proxyHostName = userObj.value + ":" + passwdObj.value + "@" + proxyHostName;
+            proxyHostName =
+              userObj.value + ":" + passwdObj.value + "@" + proxyHostName;
           }
         }
         if (proxyHostName && proxyHostPort) {
           proxyHost = "http://" + proxyHostName + ":" + proxyHostPort;
         }
       }
     }
 
     return proxyHost;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/key.jsm
+++ b/mail/extensions/openpgp/content/modules/key.jsm
@@ -3,133 +3,154 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailKey"];
 
-const KEY_BLOCK_UNKNOWN = 0;
-const KEY_BLOCK_KEY = 1;
-const KEY_BLOCK_REVOCATION = 2;
-
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const getKeyRing = EnigmailLazy.loader("enigmail/keyRing.jsm", "EnigmailKeyRing");
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const getKeyRing = EnigmailLazy.loader(
+  "enigmail/keyRing.jsm",
+  "EnigmailKeyRing"
+);
 const getDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
-
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 var EnigmailKey = {
   /**
    * Format a key fingerprint
    * @fingerprint |string|  -  unformated OpenPGP fingerprint
    *
    * @return |string| - formatted string
    */
-  formatFpr: function(fingerprint) {
+  formatFpr(fingerprint) {
     //EnigmailLog.DEBUG("key.jsm: EnigmailKey.formatFpr(" + fingerprint + ")\n");
     // format key fingerprint
     let r = "";
-    const fpr = fingerprint.match(/(....)(....)(....)(....)(....)(....)(....)(....)(....)?(....)?/);
+    const fpr = fingerprint.match(
+      /(....)(....)(....)(....)(....)(....)(....)(....)(....)?(....)?/
+    );
     if (fpr && fpr.length > 2) {
       fpr.shift();
       r = fpr.join(" ");
     }
 
     return r;
   },
 
   // Extract public key from Status Message
-  extractPubkey: function(statusMsg) {
+  extractPubkey(statusMsg) {
     const matchb = statusMsg.match(/(^|\n)NO_PUBKEY (\w{8})(\w{8})/);
-    if (matchb && (matchb.length > 3)) {
-      EnigmailLog.DEBUG("enigmailCommon.jsm:: Enigmail.extractPubkey: NO_PUBKEY 0x" + matchb[3] + "\n");
+    if (matchb && matchb.length > 3) {
+      EnigmailLog.DEBUG(
+        "enigmailCommon.jsm:: Enigmail.extractPubkey: NO_PUBKEY 0x" +
+          matchb[3] +
+          "\n"
+      );
       return matchb[2] + matchb[3];
-    } else {
-      return null;
     }
+    return null;
   },
 
   /**
    * import a revocation certificate form a given keyblock string.
    * Ask the user before importing the cert, and display an error
    * message in case of failures.
    */
-  importRevocationCert: function(keyId, keyBlockStr) {
-
+  importRevocationCert(keyId, keyBlockStr) {
     let key = getKeyRing().getKeyById(keyId);
 
     if (key) {
       if (key.keyTrust === "r") {
         // Key has already been revoked
-        getDialog().info(null, EnigmailLocale.getString("revokeKeyAlreadyRevoked", keyId));
+        getDialog().info(
+          null,
+          EnigmailLocale.getString("revokeKeyAlreadyRevoked", keyId)
+        );
       } else {
-
         let userId = key.userId + " - 0x" + key.keyId;
-        if (!getDialog().confirmDlg(null,
+        if (
+          !getDialog().confirmDlg(
+            null,
             EnigmailLocale.getString("revokeKeyQuestion", userId),
-            EnigmailLocale.getString("keyMan.button.revokeKey"))) {
+            EnigmailLocale.getString("keyMan.button.revokeKey")
+          )
+        ) {
           return;
         }
 
         let errorMsgObj = {};
-        if (getKeyRing().importKey(null, false, keyBlockStr, keyId, errorMsgObj) > 0) {
+        if (
+          getKeyRing().importKey(null, false, keyBlockStr, keyId, errorMsgObj) >
+          0
+        ) {
           getDialog().alert(null, errorMsgObj.value);
         }
       }
     } else {
       // Suitable key for revocation certificate is not present in keyring
-      getDialog().alert(null, EnigmailLocale.getString("revokeKeyNotPresent", keyId));
+      getDialog().alert(
+        null,
+        EnigmailLocale.getString("revokeKeyNotPresent", keyId)
+      );
     }
   },
 
   /**
    * Get details (key ID, UID) of the data contained in a OpenPGP key block
    *
    * @param keyBlockStr  String: the contents of one or more public keys
    * @param errorMsgObj  Object: obj.value will contain an error message in case of failures
    * @param interactive  Boolean: if in interactive mode, may display dialogs (default: true)
    *
    * @return Array of objects with the following structure:
    *          - id (key ID)
    *          - fpr
    *          - name (the UID of the key)
    *          - state (one of "old" [existing key], "new" [new key], "invalid" [key cannot not be imported])
    */
-  getKeyListFromKeyBlock: function(keyBlockStr, errorMsgObj, interactive = true) {
+  getKeyListFromKeyBlock(keyBlockStr, errorMsgObj, interactive = true) {
     EnigmailLog.DEBUG("key.jsm: getKeyListFromKeyBlock\n");
 
     const cApi = EnigmailCryptoAPI();
     let keyList = [];
     let key = {};
     let blocks;
     errorMsgObj.value = "";
 
     try {
       keyList = cApi.sync(cApi.getKeyListFromKeyBlock(keyBlockStr));
     } catch (ex) {
       errorMsgObj.value = ex.toString();
       return [];
     }
 
-
     let retArr = [];
     for (let k in keyList) {
       retArr.push(keyList[k]);
     }
 
     if (interactive && retArr.length === 1) {
       key = retArr[0];
-      if (("revoke" in key) && (!("name" in key))) {
+      if ("revoke" in key && !("name" in key)) {
         this.importRevocationCert(key.id, blocks.join("\n"));
         return [];
       }
     }
 
     return retArr;
   },
 
@@ -137,42 +158,41 @@ var EnigmailKey = {
    * Get details of a key block to import. Works identically as getKeyListFromKeyBlock();
    * except that the input is a file instead of a string
    *
    * @param file         nsIFile object - file to read
    * @param errorMsgObj  Object - obj.value will contain error message
    *
    * @return Array (same as for getKeyListFromKeyBlock())
    */
-  getKeyListFromKeyFile: function(path, errorMsgObj) {
+  getKeyListFromKeyFile(path, errorMsgObj) {
     var contents = EnigmailFiles.readFile(path);
     return this.getKeyListFromKeyBlock(contents, errorMsgObj);
   },
 
-
   /**
    * Compare 2 KeyIds of possible different length (short, long, FPR-length, with or without prefixed
    * 0x are accepted)
    *
    * @param keyId1       string
    * @param keyId2       string
    *
    * @return true or false, given the comparison of the last minimum-length characters.
    */
-  compareKeyIds: function(keyId1, keyId2) {
+  compareKeyIds(keyId1, keyId2) {
     var keyId1Raw = keyId1.replace(/^0x/, "").toUpperCase();
     var keyId2Raw = keyId2.replace(/^0x/, "").toUpperCase();
 
     var minlength = Math.min(keyId1Raw.length, keyId2Raw.length);
 
     if (minlength < keyId1Raw.length) {
       // Limit keyId1 to minlength
       keyId1Raw = keyId1Raw.substr(-minlength, minlength);
     }
 
     if (minlength < keyId2Raw.length) {
       // Limit keyId2 to minlength
       keyId2Raw = keyId2Raw.substr(-minlength, minlength);
     }
 
-    return (keyId1Raw === keyId2Raw);
-  }
+    return keyId1Raw === keyId2Raw;
+  },
 };
--- a/mail/extensions/openpgp/content/modules/keyObj.jsm
+++ b/mail/extensions/openpgp/content/modules/keyObj.jsm
@@ -3,17 +3,16 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["newEnigmailKeyObj"];
 
-
 /**
  This module implements the EnigmailKeyObj class with the following members:
 
   - keyId           - 16 digits (8-byte) public key ID (/not/ preceeded with 0x)
   - userId          - main user ID
   - fpr             - fingerprint
   - fprFormatted    - a formatted version of the fingerprint followin the scheme .... .... ....
   - expiry          - Expiry date as printable string
@@ -58,22 +57,34 @@ var EXPORTED_SYMBOLS = ["newEnigmailKeyO
      * getEncryptionValidity
      * getSigningValidity
      * getPubKeyValidity
      * clone
      * getMinimalPubKey
      * getVirtualKeySize
 */
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailKey = ChromeUtils.import(
+  "chrome://openpgp/content/modules/key.jsm"
+).EnigmailKey;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailTime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/time.jsm"
+).EnigmailTime;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 function newEnigmailKeyObj(keyData) {
   return new EnigmailKeyObj(keyData);
 }
 
 class EnigmailKeyObj {
   constructor(keyData) {
     this.keyId = "";
@@ -90,25 +101,38 @@ class EnigmailKeyObj {
     this.subKeys = [];
     this.fpr = "";
     this.minimalKeyBlock = [];
     this.photoAvailable = false;
     this.secretAvailable = false;
     this._sigList = null;
 
     this.type = keyData.type;
-    if ("keyId" in keyData) this.keyId = keyData.keyId;
+    if ("keyId" in keyData) {
+      this.keyId = keyData.keyId;
+    }
     if ("expiryTime" in keyData) {
       this.expiryTime = keyData.expiryTime;
       this.expiry = EnigmailTime.getDateTime(keyData.expiryTime, true, false);
     }
 
     const ATTRS = [
-      "created", "keyCreated", "keyTrust", "keyUseFor", "ownerTrust", "algoSym", "keySize",
-      "userIds", "subKeys", "fpr", "secretAvailable", "photoAvailable", "userId"
+      "created",
+      "keyCreated",
+      "keyTrust",
+      "keyUseFor",
+      "ownerTrust",
+      "algoSym",
+      "keySize",
+      "userIds",
+      "subKeys",
+      "fpr",
+      "secretAvailable",
+      "photoAvailable",
+      "userId",
     ];
     for (let i of ATTRS) {
       if (i in keyData) {
         this[i] = keyData[i];
       }
     }
   }
 
@@ -137,148 +161,194 @@ class EnigmailKeyObj {
     let cp = new EnigmailKeyObj(["copy"]);
     for (let i in this) {
       if (i !== "signatures" && i !== "fprFormatted") {
         // caution: don't try to evaluate this[i] if i==="signatures";
         // it would immediately get all signatures for the key (slow!)
         if (typeof this[i] !== "function") {
           if (typeof this[i] === "object") {
             cp[i] = EnigmailFuncs.cloneObj(this[i]);
-          } else
+          } else {
             cp[i] = this[i];
+          }
         }
       }
     }
 
     return cp;
   }
 
   /**
    * Does the key have secondary user IDs?
    *
    * @return: Boolean - true if yes; false if no
    */
   hasSubUserIds() {
     let nUid = 0;
     for (let i in this.userIds) {
-      if (this.userIds[i].type === "uid") ++nUid;
+      if (this.userIds[i].type === "uid") {
+        ++nUid;
+      }
     }
 
     return nUid >= 2;
   }
 
   /**
    * Get a formatted version of the fingerprint:
    * 1234 5678 90AB CDEF .... ....
    *
    * @return String - the formatted fingerprint
    */
   get fprFormatted() {
     let f = EnigmailKey.formatFpr(this.fpr);
-    if (f.length === 0) f = this.fpr;
+    if (f.length === 0) {
+      f = this.fpr;
+    }
     return f;
   }
 
   /**
    * Is the function to set owner trust available for the key?
    * Requirements: The key is signed with at least medium validity level,
    * or the secret key is available.
    *
    * @return Boolean true if yes
    */
   isOwnerTrustUseful() {
-    if (this.secretAvailable) return true;
-    if (this.keyTrust.search(/^[fu]/) === 0) return true;
+    if (this.secretAvailable) {
+      return true;
+    }
+    if (this.keyTrust.search(/^[fu]/) === 0) {
+      return true;
+    }
 
     return false;
   }
 
   /**
    * Determine if the public key is valid. If not, return a description why it's not
    *
    * @return Object:
    *   - keyValid: Boolean (true if key is valid)
    *   - reason: String (explanation of invalidity)
    */
   getPubKeyValidity() {
     let retVal = {
       keyValid: false,
-      reason: ""
+      reason: "",
     };
     if (this.keyTrust.search(/r/i) >= 0) {
       // public key revoked
-      retVal.reason = EnigmailLocale.getString("keyRing.pubKeyRevoked", [this.userId, "0x" + this.keyId]);
+      retVal.reason = EnigmailLocale.getString("keyRing.pubKeyRevoked", [
+        this.userId,
+        "0x" + this.keyId,
+      ]);
     } else if (this.keyTrust.search(/e/i) >= 0) {
       // public key expired
-      retVal.reason = EnigmailLocale.getString("keyRing.pubKeyExpired", [this.userId, "0x" + this.keyId]);
-    } else if (this.keyTrust.search(/d/i) >= 0 || this.keyUseFor.search(/D/i) >= 0) {
+      retVal.reason = EnigmailLocale.getString("keyRing.pubKeyExpired", [
+        this.userId,
+        "0x" + this.keyId,
+      ]);
+    } else if (
+      this.keyTrust.search(/d/i) >= 0 ||
+      this.keyUseFor.search(/D/i) >= 0
+    ) {
       // public key disabled
-      retVal.reason = EnigmailLocale.getString("keyRing.keyDisabled", [this.userId, "0x" + this.keyId]);
+      retVal.reason = EnigmailLocale.getString("keyRing.keyDisabled", [
+        this.userId,
+        "0x" + this.keyId,
+      ]);
     } else if (this.keyTrust.search(/i/i) >= 0) {
       // public key invalid
-      retVal.reason = EnigmailLocale.getString("keyRing.keyInvalid", [this.userId, "0x" + this.keyId]);
+      retVal.reason = EnigmailLocale.getString("keyRing.keyInvalid", [
+        this.userId,
+        "0x" + this.keyId,
+      ]);
     } else {
       retVal.keyValid = true;
     }
 
     return retVal;
   }
 
-
   /**
    * Check whether a key can be used for signing and return a description of why not
    *
    * @return Object:
    *   - keyValid: Boolean (true if key is valid)
    *   - reason: String (explanation of invalidity)
    */
   getSigningValidity() {
     let retVal = this.getPubKeyValidity();
 
-    if (!retVal.keyValid) return retVal;
+    if (!retVal.keyValid) {
+      return retVal;
+    }
 
     if (!this.secretAvailable) {
-      retVal.reason = EnigmailLocale.getString("keyRing.noSecretKey", [this.userId, "0x" + this.keyId]);
+      retVal.reason = EnigmailLocale.getString("keyRing.noSecretKey", [
+        this.userId,
+        "0x" + this.keyId,
+      ]);
       retVal.keyValid = false;
     } else if (this.keyUseFor.search(/S/) < 0) {
       retVal.keyValid = false;
 
       if (this.keyTrust.search(/u/i) < 0) {
         // public key invalid
-        retVal.reason = EnigmailLocale.getString("keyRing.keyNotTrusted", [this.userId, "0x" + this.keyId]);
+        retVal.reason = EnigmailLocale.getString("keyRing.keyNotTrusted", [
+          this.userId,
+          "0x" + this.keyId,
+        ]);
       } else {
         let expired = 0,
           revoked = 0,
           unusable = 0,
           found = 0;
         // public key is valid; check for signing subkeys
         for (let sk in this.subKeys) {
           if (this.subKeys[sk].keyUseFor.search(/S/) >= 0) {
             if (this.subKeys[sk].keyTrust.search(/e/i) >= 0) {
               ++expired;
             } else if (this.subKeys[sk].keyTrust.search(/r/i) >= 0) {
               ++revoked;
-            } else if (this.subKeys[sk].keyTrust.search(/[di-]/i) >= 0 || this.subKeys[sk].keyUseFor.search(/D/) >= 0) {
+            } else if (
+              this.subKeys[sk].keyTrust.search(/[di-]/i) >= 0 ||
+              this.subKeys[sk].keyUseFor.search(/D/) >= 0
+            ) {
               ++unusable;
             } else {
               // found subkey usable
               ++found;
             }
           }
         }
 
         if (!found) {
           if (expired) {
-            retVal.reason = EnigmailLocale.getString("keyRing.signSubKeysExpired", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.signSubKeysExpired",
+              [this.userId, "0x" + this.keyId]
+            );
           } else if (revoked) {
-            retVal.reason = EnigmailLocale.getString("keyRing.signSubKeysRevoked", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.signSubKeysRevoked",
+              [this.userId, "0x" + this.keyId]
+            );
           } else if (unusable) {
-            retVal.reason = EnigmailLocale.getString("keyRing.signSubKeysUnusable", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.signSubKeysUnusable",
+              [this.userId, "0x" + this.keyId]
+            );
           } else {
-            retVal.reason = EnigmailLocale.getString("keyRing.pubKeyNotForSigning", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.pubKeyNotForSigning",
+              [this.userId, "0x" + this.keyId]
+            );
           }
         } else {
           retVal.keyValid = true;
         }
       }
     }
 
     console.debug("getSigningValidity retVal: %o", retVal);
@@ -289,55 +359,75 @@ class EnigmailKeyObj {
    * Check whether a key can be used for encryption and return a description of why not
    *
    * @return Object:
    *   - keyValid: Boolean (true if key is valid)
    *   - reason: String (explanation of invalidity)
    */
   getEncryptionValidity() {
     let retVal = this.getPubKeyValidity();
-    if (!retVal.keyValid) return retVal;
+    if (!retVal.keyValid) {
+      return retVal;
+    }
 
     if (this.keyUseFor.search(/E/) < 0) {
       retVal.keyValid = false;
 
       if (this.keyTrust.search(/u/i) < 0) {
         // public key invalid
-        retVal.reason = EnigmailLocale.getString("keyRing.keyInvalid", [this.userId, "0x" + this.keyId]);
+        retVal.reason = EnigmailLocale.getString("keyRing.keyInvalid", [
+          this.userId,
+          "0x" + this.keyId,
+        ]);
       } else {
         let expired = 0,
           revoked = 0,
           unusable = 0,
           found = 0;
         // public key is valid; check for encryption subkeys
 
         for (let sk in this.subKeys) {
           if (this.subKeys[sk].keyUseFor.search(/E/) >= 0) {
             if (this.subKeys[sk].keyTrust.search(/e/i) >= 0) {
               ++expired;
             } else if (this.subKeys[sk].keyTrust.search(/r/i) >= 0) {
               ++revoked;
-            } else if (this.subKeys[sk].keyTrust.search(/[di-]/i) >= 0 || this.subKeys[sk].keyUseFor.search(/D/) >= 0) {
+            } else if (
+              this.subKeys[sk].keyTrust.search(/[di-]/i) >= 0 ||
+              this.subKeys[sk].keyUseFor.search(/D/) >= 0
+            ) {
               ++unusable;
             } else {
               // found subkey usable
               ++found;
             }
           }
         }
 
         if (!found) {
           if (expired) {
-            retVal.reason = EnigmailLocale.getString("keyRing.encSubKeysExpired", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.encSubKeysExpired",
+              [this.userId, "0x" + this.keyId]
+            );
           } else if (revoked) {
-            retVal.reason = EnigmailLocale.getString("keyRing.encSubKeysRevoked", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.encSubKeysRevoked",
+              [this.userId, "0x" + this.keyId]
+            );
           } else if (unusable) {
-            retVal.reason = EnigmailLocale.getString("keyRing.encSubKeysUnusable", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.encSubKeysUnusable",
+              [this.userId, "0x" + this.keyId]
+            );
           } else {
-            retVal.reason = EnigmailLocale.getString("keyRing.pubKeyNotForEncryption", [this.userId, "0x" + this.keyId]);
+            retVal.reason = EnigmailLocale.getString(
+              "keyRing.pubKeyNotForEncryption",
+              [this.userId, "0x" + this.keyId]
+            );
           }
         } else {
           retVal.keyValid = true;
         }
       }
     }
 
     console.debug("getEncryptionValidity retVal: %o", retVal);
@@ -351,30 +441,33 @@ class EnigmailKeyObj {
    *
    * @return Number - The expiry date as seconds after 01/01/1970
    */
   getKeyExpiry() {
     let expiryDate = Number.MAX_VALUE;
     let encryption = -1;
     let signing = -1;
 
-
     // check public key expiry date
     if (this.expiryTime > 0) {
       expiryDate = this.expiryTime;
     }
 
     for (let sk in this.subKeys) {
       if (this.subKeys[sk].keyUseFor.search(/[eE]/) >= 0) {
         let expiry = this.subKeys[sk].expiryTime;
-        if (expiry === 0) expiry = Number.MAX_VALUE;
+        if (expiry === 0) {
+          expiry = Number.MAX_VALUE;
+        }
         encryption = Math.max(encryption, expiry);
       } else if (this.subKeys[sk].keyUseFor.search(/[sS]/) >= 0) {
         let expiry = this.subKeys[sk].expiryTime;
-        if (expiry === 0) expiry = Number.MAX_VALUE;
+        if (expiry === 0) {
+          expiry = Number.MAX_VALUE;
+        }
         signing = Math.max(signing, expiry);
       }
     }
 
     if (expiryDate > encryption) {
       if (this.keyUseFor.search(/[eE]/) < 0) {
         expiryDate = encryption;
       }
@@ -397,41 +490,44 @@ class EnigmailKeyObj {
    *
    * @return Object:
    *    - exitCode (0 = success)
    *    - errorMsg (if exitCode != 0)
    *    - keyData: BASE64-encded string of key data
    */
 
   getMinimalPubKey(emailAddr) {
-    EnigmailLog.DEBUG("keyObj.jsm: EnigmailKeyObj.getMinimalPubKey: " + this.keyId + "\n");
+    EnigmailLog.DEBUG(
+      "keyObj.jsm: EnigmailKeyObj.getMinimalPubKey: " + this.keyId + "\n"
+    );
 
     if (emailAddr) {
       try {
         emailAddr = EnigmailFuncs.stripEmail(emailAddr.toLowerCase());
       } catch (x) {
         emailAddr = emailAddr.toLowerCase();
       }
 
-
       let foundUid = false,
         uid = "";
       for (let i in this.userIds) {
         try {
           uid = EnigmailFuncs.stripEmail(this.userIds[i].userId.toLowerCase());
         } catch (x) {
           uid = this.userIds[i].userId.toLowerCase();
         }
 
         if (uid == emailAddr) {
           foundUid = true;
           break;
         }
       }
-      if (!foundUid) emailAddr = false;
+      if (!foundUid) {
+        emailAddr = false;
+      }
     }
 
     if (!emailAddr) {
       emailAddr = this.userId;
     }
 
     try {
       emailAddr = EnigmailFuncs.stripEmail(emailAddr.toLowerCase());
@@ -440,62 +536,69 @@ class EnigmailKeyObj {
     }
 
     let newestSigningKey = 0,
       newestEncryptionKey = 0,
       subkeysArr = null;
 
     // search for valid subkeys
     for (let sk in this.subKeys) {
-      if ("indDre".indexOf(this.subKeys[sk].keyTrust) < 0) {
+      if (!"indDre".includes(this.subKeys[sk].keyTrust)) {
         if (this.subKeys[sk].keyUseFor.search(/[sS]/) >= 0) {
           // found signing subkey
-          if (this.subKeys[sk].keyCreated > newestSigningKey) newestSigningKey = this.subKeys[sk].keyCreated;
+          if (this.subKeys[sk].keyCreated > newestSigningKey) {
+            newestSigningKey = this.subKeys[sk].keyCreated;
+          }
         }
         if (this.subKeys[sk].keyUseFor.search(/[eE]/) >= 0) {
           // found encryption subkey
-          if (this.subKeys[sk].keyCreated > newestEncryptionKey) newestEncryptionKey = this.subKeys[sk].keyCreated;
+          if (this.subKeys[sk].keyCreated > newestEncryptionKey) {
+            newestEncryptionKey = this.subKeys[sk].keyCreated;
+          }
         }
       }
     }
 
     if (newestSigningKey > 0 && newestEncryptionKey > 0) {
       subkeysArr = [newestEncryptionKey, newestSigningKey];
     }
 
     if (!(emailAddr in this.minimalKeyBlock)) {
       const cApi = EnigmailCryptoAPI();
-      this.minimalKeyBlock[emailAddr] = cApi.sync(cApi.getMinimalPubKey(this.fpr, emailAddr, subkeysArr));
+      this.minimalKeyBlock[emailAddr] = cApi.sync(
+        cApi.getMinimalPubKey(this.fpr, emailAddr, subkeysArr)
+      );
     }
     return this.minimalKeyBlock[emailAddr];
   }
 
   /**
    * Obtain a "virtual" key size that allows to compare different algorithms with each other
    * e.g. elliptic curve keys have small key sizes with high cryptographic strength
    *
    *
    * @return Number: a virtual size
    */
   getVirtualKeySize() {
-    EnigmailLog.DEBUG("keyObj.jsm: EnigmailKeyObj.getVirtualKeySize: " + this.keyId + "\n");
+    EnigmailLog.DEBUG(
+      "keyObj.jsm: EnigmailKeyObj.getVirtualKeySize: " + this.keyId + "\n"
+    );
 
     switch (this.algoSym) {
       case "DSA":
         return this.keySize / 2;
       case "ECDSA":
         return this.keySize * 8;
       case "EDDSA":
         return this.keySize * 32;
       default:
         return this.keySize;
     }
   }
 
-
   /**
    * Get a file object holding the photo of a key
    *
    * @param {Number} photoNumber: number of the photo on the key, starting with 0
    *
    * @return {nsIFile} object or null in case no data / error.
    */
   getPhotoFile(photoNumber) {
--- a/mail/extensions/openpgp/content/modules/keyRefreshService.jsm
+++ b/mail/extensions/openpgp/content/modules/keyRefreshService.jsm
@@ -3,126 +3,160 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailKeyRefreshService"];
 
-
-
-
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailRNG = ChromeUtils.import("chrome://openpgp/content/modules/rng.jsm").EnigmailRNG;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailKeyServer = ChromeUtils.import("chrome://openpgp/content/modules/keyserver.jsm").EnigmailKeyServer;
-const EnigmailKeyserverURIs = ChromeUtils.import("chrome://openpgp/content/modules/keyserverUris.jsm").EnigmailKeyserverURIs;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailRNG = ChromeUtils.import(
+  "chrome://openpgp/content/modules/rng.jsm"
+).EnigmailRNG;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailKeyServer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyserver.jsm"
+).EnigmailKeyServer;
+const EnigmailKeyserverURIs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyserverUris.jsm"
+).EnigmailKeyserverURIs;
 
-const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
 const ONE_HOUR_IN_MILLISEC = 60 * 60 * 1000;
 
 let gTimer = null;
 
 function getTimer() {
-  if (gTimer === null) gTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+  if (gTimer === null) {
+    gTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+  }
   return gTimer;
 }
 
 const HOURS_PER_WEEK_ENIGMAIL_IS_ON_PREF = "hoursPerWeekEnigmailIsOn";
 const SECONDS_MIN_DELAY = "refreshMinDelaySeconds";
 
 function calculateMaxTimeForRefreshInMilliseconds(totalPublicKeys) {
-  const millisecondsAvailableForRefresh = EnigmailPrefs.getPref(HOURS_PER_WEEK_ENIGMAIL_IS_ON_PREF) * ONE_HOUR_IN_MILLISEC;
+  const millisecondsAvailableForRefresh =
+    EnigmailPrefs.getPref(HOURS_PER_WEEK_ENIGMAIL_IS_ON_PREF) *
+    ONE_HOUR_IN_MILLISEC;
   return Math.floor(millisecondsAvailableForRefresh / totalPublicKeys);
 }
 
 function calculateWaitTimeInMilliseconds(totalPublicKeys) {
   const randomNumber = EnigmailRNG.generateRandomUint32();
-  const maxTimeForRefresh = calculateMaxTimeForRefreshInMilliseconds(totalPublicKeys);
+  const maxTimeForRefresh = calculateMaxTimeForRefreshInMilliseconds(
+    totalPublicKeys
+  );
   const minDelay = EnigmailPrefs.getPref(SECONDS_MIN_DELAY) * 1000;
 
-  EnigmailLog.DEBUG("keyRefreshService.jsm: Wait time = random number: " + randomNumber + " % max time for refresh: " + maxTimeForRefresh + "\n");
+  EnigmailLog.DEBUG(
+    "keyRefreshService.jsm: Wait time = random number: " +
+      randomNumber +
+      " % max time for refresh: " +
+      maxTimeForRefresh +
+      "\n"
+  );
 
   let millisec = randomNumber % maxTimeForRefresh;
   if (millisec < minDelay) {
     millisec += minDelay;
   }
 
-  EnigmailLog.DEBUG("keyRefreshService.jsm: Time until next refresh in milliseconds: " + millisec + "\n");
+  EnigmailLog.DEBUG(
+    "keyRefreshService.jsm: Time until next refresh in milliseconds: " +
+      millisec +
+      "\n"
+  );
 
   return millisec;
 }
 
 function refreshKey() {
   const timer = getTimer();
   refreshWith(EnigmailKeyServer, timer, true);
 }
 
 function restartTimerInOneHour(timer) {
-  timer.initWithCallback(refreshKey,
+  timer.initWithCallback(
+    refreshKey,
     ONE_HOUR_IN_MILLISEC,
-    Ci.nsITimer.TYPE_ONE_SHOT);
+    Ci.nsITimer.TYPE_ONE_SHOT
+  );
 }
 
 function setupNextRefresh(timer, waitTime) {
-  timer.initWithCallback(refreshKey,
-    waitTime,
-    Ci.nsITimer.TYPE_ONE_SHOT);
+  timer.initWithCallback(refreshKey, waitTime, Ci.nsITimer.TYPE_ONE_SHOT);
 }
 
 function logMissingInformation(keyIdsExist, validKeyserversExist) {
   if (!keyIdsExist) {
-    EnigmailLog.DEBUG("keyRefreshService.jsm: No keys available to refresh yet. Will recheck in an hour.\n");
+    EnigmailLog.DEBUG(
+      "keyRefreshService.jsm: No keys available to refresh yet. Will recheck in an hour.\n"
+    );
   }
   if (!validKeyserversExist) {
-    EnigmailLog.DEBUG("keyRefreshService.jsm: Either no keyservers exist or the protocols specified are invalid. Will recheck in an hour.\n");
+    EnigmailLog.DEBUG(
+      "keyRefreshService.jsm: Either no keyservers exist or the protocols specified are invalid. Will recheck in an hour.\n"
+    );
   }
 }
 
 function getRandomKeyId(randomNumber) {
   const keyRingLength = EnigmailKeyRing.getAllKeys().keyList.length;
 
   if (keyRingLength === 0) {
     return null;
   }
 
-  return EnigmailKeyRing.getAllKeys().keyList[randomNumber % keyRingLength].keyId;
+  return EnigmailKeyRing.getAllKeys().keyList[randomNumber % keyRingLength]
+    .keyId;
 }
 
 function refreshKeyIfReady(keyserver, readyToRefresh, keyId) {
   if (readyToRefresh) {
-    EnigmailLog.DEBUG("keyRefreshService.jsm: refreshing key ID " + keyId + "\n");
+    EnigmailLog.DEBUG(
+      "keyRefreshService.jsm: refreshing key ID " + keyId + "\n"
+    );
     return keyserver.download(keyId);
   }
-  else {
-    return Promise.resolve(0);
-  }
+
+  return Promise.resolve(0);
 }
 
 async function refreshWith(keyserver, timer, readyToRefresh) {
   const keyId = getRandomKeyId(EnigmailRNG.generateRandomUint32());
   const keyIdsExist = keyId !== null;
   const validKeyserversExist = EnigmailKeyserverURIs.validKeyserversExist();
-  const ioService = Cc[IOSERVICE_CONTRACTID].getService(Ci.nsIIOService);
+  const ioService = Services.io;
 
   if (keyIdsExist && validKeyserversExist) {
-    if (ioService && (!ioService.offline)) {
+    if (ioService && !ioService.offline) {
       // don't try to refresh if we are offline
       await refreshKeyIfReady(keyserver, readyToRefresh, keyId);
-    }
-    else {
-      EnigmailLog.DEBUG("keyRefreshService.jsm: offline - not refreshing any key\n");
+    } else {
+      EnigmailLog.DEBUG(
+        "keyRefreshService.jsm: offline - not refreshing any key\n"
+      );
     }
-    const waitTime = calculateWaitTimeInMilliseconds(EnigmailKeyRing.getAllKeys().keyList.length);
+    const waitTime = calculateWaitTimeInMilliseconds(
+      EnigmailKeyRing.getAllKeys().keyList.length
+    );
     setupNextRefresh(timer, waitTime);
-  }
-  else {
+  } else {
     logMissingInformation(keyIdsExist, validKeyserversExist);
     restartTimerInOneHour(timer);
   }
 }
 
 /**
  * Starts a process to continuously refresh keys on a random time interval and in random order.
  *
@@ -144,10 +178,10 @@ function start(keyserver) {
   }
 }
 
 /*
   This module intializes the continuous key refresh functionality. This includes randomly selecting th key to refresh and the timing to wait between each refresh
 */
 
 var EnigmailKeyRefreshService = {
-  start: start
+  start,
 };
--- a/mail/extensions/openpgp/content/modules/keyRing.jsm
+++ b/mail/extensions/openpgp/content/modules/keyRing.jsm
@@ -3,43 +3,54 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailKeyRing"];
 
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailTrust = ChromeUtils.import("chrome://openpgp/content/modules/trust.jsm").EnigmailTrust;
-const EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-const EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const newEnigmailKeyObj = ChromeUtils.import("chrome://openpgp/content/modules/keyObj.jsm").newEnigmailKeyObj;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
-
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailTrust = ChromeUtils.import(
+  "chrome://openpgp/content/modules/trust.jsm"
+).EnigmailTrust;
+const EnigmailArmor = ChromeUtils.import(
+  "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const newEnigmailKeyObj = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyObj.jsm"
+).newEnigmailKeyObj;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 const getDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
-const getWindows = EnigmailLazy.loader("enigmail/windows.jsm", "EnigmailWindows");
-const getKeyUsability = EnigmailLazy.loader("enigmail/keyUsability.jsm", "EnigmailKeyUsability");
+const getWindows = EnigmailLazy.loader(
+  "enigmail/windows.jsm",
+  "EnigmailWindows"
+);
 
 const DEFAULT_FILE_PERMS = 0o600;
 
 let gKeyListObj = null;
 let gKeyIndex = [];
 let gSubkeyIndex = [];
-let gKeyCheckDone = false;
 let gLoadingKeys = false;
 
 /*
 
   This module operates with a Key Store (array) containing objects with the following properties:
 
   * keyList [Array] of EnigmailKeyObj
 
@@ -54,106 +65,110 @@ let gLoadingKeys = false;
             - T: TOFU
             - TP: TOFU+PGP
 
 */
 
 const TRUSTLEVELS_SORTED = EnigmailTrust.trustLevelsSorted();
 
 var EnigmailKeyRing = {
-
   /**
    * Get the complete list of all public keys, optionally sorted by a column
    *
    * @param  win           - optional |object| holding the parent window for displaying error messages
    * @param  sortColumn    - optional |string| containing the column name for sorting. One of:
    *                            userid, keyid, keyidshort, fpr, keytype, validity, trust, expiry
    * @param  sortDirection - |number| 1 = ascending / -1 = descending
    *
    * @return keyListObj    - |object| { keyList, keySortList } (see above)
    */
-  getAllKeys: function(win, sortColumn, sortDirection) {
+  getAllKeys(win, sortColumn, sortDirection) {
     console.debug("keyring.getAllKeys");
     if (gKeyListObj.keySortList.length === 0) {
       console.debug("keyring.getAllKeys - loadkeylist");
       loadKeyList(win, sortColumn, sortDirection);
       console.debug("keyring.getAllKeys - keymanreloadkeys");
-//getWindows().keyManReloadKeys();
+      //getWindows().keyManReloadKeys();
       /* TODO: do we need something similar with TB's future trust behavior?
       if (!gKeyCheckDone) {
         gKeyCheckDone = true;
         runKeyUsabilityCheck();
       }
       */
-    }
-    else {
-      if (sortColumn) {
-        gKeyListObj.keySortList.sort(getSortFunction(sortColumn.toLowerCase(), gKeyListObj, sortDirection));
-      }
+    } else if (sortColumn) {
+      gKeyListObj.keySortList.sort(
+        getSortFunction(sortColumn.toLowerCase(), gKeyListObj, sortDirection)
+      );
     }
 
     return gKeyListObj;
   },
 
   /**
    * get a list of all (valid, usable) keys that have a secret key
    *
    * @param Boolean onlyValidKeys: if true, only filter valid usable keys
    *
    * @return Array of KeyObjects containing the found keys (sorted by userId)
    **/
 
-  getAllSecretKeys: function(onlyValidKeys = false) {
+  getAllSecretKeys(onlyValidKeys = false) {
     EnigmailLog.DEBUG("keyRing.jsm: getAllSecretKeys()\n");
 
     let res = [];
 
     this.getAllKeys(); // ensure keylist is loaded;
 
     if (!onlyValidKeys) {
       for (let key of gKeyListObj.keyList) {
-        if (key.secretAvailable) res.push(key);
+        if (key.secretAvailable) {
+          res.push(key);
+        }
       }
-    }
-    else {
+    } else {
       for (let key of gKeyListObj.keyList) {
         if (key.secretAvailable && key.keyUseFor.search(/D/) < 0) {
           // key is not disabled and _usable_ for encryption signing and certification
-          if (key.keyUseFor.search(/E/) >= 0 &&
+          if (
+            key.keyUseFor.search(/E/) >= 0 &&
             key.keyUseFor.search(/S/) >= 0 &&
-            key.keyUseFor.search(/C/) >= 0) {
+            key.keyUseFor.search(/C/) >= 0
+          ) {
             res.push(key);
           }
         }
       }
     }
 
     res.sort(function(a, b) {
-      return a.userId == b.userId ? (a.keyId < b.keyId ? -1 : 1) : (a.userId.toLowerCase() < b.userId.toLowerCase() ? -1 : 1);
+      if (a.userId == b.userId) {
+        return a.keyId < b.keyId ? -1 : 1;
+      }
+      return a.userId.toLowerCase() < b.userId.toLowerCase() ? -1 : 1;
     });
 
     return res;
   },
 
-
   /**
    * get 1st key object that matches a given key ID or subkey ID
    *
    * @param keyId      - String: key Id with 16 characters (preferred) or 8 characters),
    *                             or fingerprint (40 or 32 characters).
    *                             Optionally preceeded with "0x"
    * @param noLoadKeys - Boolean [optional]: do not try to load the key list first
    *
    * @return Object - found KeyObject or null if key not found
    */
-  getKeyById: function(keyId, noLoadKeys) {
+  getKeyById(keyId, noLoadKeys) {
     EnigmailLog.DEBUG("keyRing.jsm: getKeyById: " + keyId + "\n");
-    let s;
 
-    if (!keyId) return null;
+    if (!keyId) {
+      return null;
+    }
 
     if (keyId.search(/^0x/) === 0) {
       keyId = keyId.substr(2);
     }
 
     if (!noLoadKeys) {
       this.getAllKeys(); // ensure keylist is loaded;
     }
@@ -172,33 +187,38 @@ var EnigmailKeyRing = {
    *
    * @param searchTerm   - String: a regular expression to match against all UIDs of the keys.
    *                               The search is always performed case-insensitively
    *                               An empty string will return no result
    * @param onlyValidUid - Boolean: if true (default), invalid (e.g. revoked) UIDs are not matched
    *
    * @return Array of KeyObjects with the found keys (array length is 0 if no key found)
    */
-  getKeysByUserId: function(searchTerm, onlyValidUid = true) {
+  getKeysByUserId(searchTerm, onlyValidUid = true) {
     EnigmailLog.DEBUG("keyRing.jsm: getKeysByUserId: '" + searchTerm + "'\n");
     let s = new RegExp(searchTerm, "i");
 
     let res = [];
 
     this.getAllKeys(); // ensure keylist is loaded;
 
-    if (searchTerm === "") return res;
+    if (searchTerm === "") {
+      return res;
+    }
     console.debug(gKeyListObj.keyList);
     for (let i in gKeyListObj.keyList) {
       let k = gKeyListObj.keyList[i];
 
       for (let j in k.userIds) {
         if (k.userIds[j].type === "uid" && k.userIds[j].userId.search(s) >= 0) {
           console.debug("found " + k.userIds[j].userId);
-          if (!onlyValidUid || (!EnigmailTrust.isInvalid(k.userIds[j].keyTrust))) {
+          if (
+            !onlyValidUid ||
+            !EnigmailTrust.isInvalid(k.userIds[j].keyTrust)
+          ) {
             res.push(k);
             continue;
           }
         }
       }
     }
     console.debug("getKeysByUserId result: %o", res);
     return res;
@@ -208,172 +228,191 @@ var EnigmailKeyRing = {
    * Specialized function for getSecretKeyByUserId() that takes into account
    * the specifics of email addresses in UIDs.
    *
    * @param emailAddr: String - email address to search for without any angulars
    *                            or names
    *
    * @return KeyObject with the found key, or null if no key found
    */
-  getSecretKeyByEmail: function(emailAddr) {
+  getSecretKeyByEmail(emailAddr) {
     // sanitize email address
     emailAddr = emailAddr.replace(/([\.\[\]\-\\])/g, "\\$1");
 
-    let searchTerm = "(<" + emailAddr + ">| " + emailAddr + "$|^" + emailAddr + "$)";
+    let searchTerm =
+      "(<" + emailAddr + ">| " + emailAddr + "$|^" + emailAddr + "$)";
 
     return this.getSecretKeyByUserId(searchTerm);
   },
 
   /**
    * get the "best" possible secret key for a given user ID
    *
    * @param searchTerm   - String: a regular expression to match against all UIDs of the keys.
    *                               The search is always performed case-insensitively
    * @return KeyObject with the found key, or null if no key found
    */
-  getSecretKeyByUserId: function(searchTerm) {
-    EnigmailLog.DEBUG("keyRing.jsm: getSecretKeyByUserId: '" + searchTerm + "'\n");
+  getSecretKeyByUserId(searchTerm) {
+    EnigmailLog.DEBUG(
+      "keyRing.jsm: getSecretKeyByUserId: '" + searchTerm + "'\n"
+    );
     let keyList = this.getKeysByUserId(searchTerm, true);
-    console.debug("getSecretKeyByUserId, got result from getKeysByUserId: %o", keyList);
+    console.debug(
+      "getSecretKeyByUserId, got result from getKeysByUserId: %o",
+      keyList
+    );
 
     let foundKey = null;
 
     for (let key of keyList) {
-      if (key.secretAvailable && key.getEncryptionValidity().keyValid && key.getSigningValidity().keyValid) {
+      if (
+        key.secretAvailable &&
+        key.getEncryptionValidity().keyValid &&
+        key.getSigningValidity().keyValid
+      ) {
         if (!foundKey) {
           foundKey = key;
-        }
-        else {
-          // prefer RSA or DSA over ECC (long-term: change this once ECC keys are widely supported)
-          if (foundKey.algoSym === key.algoSym && foundKey.keySize === key.keySize) {
-            if (key.expiryTime > foundKey.expiryTime)
-              foundKey = key;
-          }
-          else if (foundKey.algoSym.search(/^(DSA|RSA)$/) < 0 && key.algoSym.search(/^(DSA|RSA)$/) === 0) {
+        } else if (
+          foundKey.algoSym === key.algoSym &&
+          foundKey.keySize === key.keySize
+        ) {
+          if (key.expiryTime > foundKey.expiryTime) {
             foundKey = key;
           }
-          else {
-            if (key.getVirtualKeySize() > foundKey.getVirtualKeySize())
-              foundKey = key;
-          }
+        } else if (
+          foundKey.algoSym.search(/^(DSA|RSA)$/) < 0 &&
+          key.algoSym.search(/^(DSA|RSA)$/) === 0
+        ) {
+          // prefer RSA or DSA over ECC (long-term: change this once ECC keys are widely supported)
+          foundKey = key;
+        } else if (key.getVirtualKeySize() > foundKey.getVirtualKeySize()) {
+          foundKey = key;
         }
       }
     }
     console.debug("getSecretKeyByUserId, foundKey: %o", foundKey);
     return foundKey;
   },
 
   /**
    * get a list of keys for a given set of (sub-) key IDs
    *
    * @param keyIdList: Array of key IDs
                        OR String, with space-separated list of key IDs
    */
-  getKeyListById: function(keyIdList) {
+  getKeyListById(keyIdList) {
     EnigmailLog.DEBUG("keyRing.jsm: getKeyListById: '" + keyIdList + "'\n");
     let keyArr;
     if (typeof keyIdList === "string") {
       keyArr = keyIdList.split(/ +/);
-    }
-    else {
+    } else {
       keyArr = keyIdList;
     }
 
     let ret = [];
     for (let i in keyArr) {
       let r = this.getKeyById(keyArr[i]);
-      if (r) ret.push(r);
+      if (r) {
+        ret.push(r);
+      }
     }
 
     return ret;
   },
 
-  importKeyFromFile: function(inputFile, errorMsgObj, importedKeysObj) {
-    EnigmailLog.DEBUG("keyRing.jsm: EnigmailKeyRing.importKeyFromFile: fileName=" + inputFile.path + "\n");
+  importKeyFromFile(inputFile, errorMsgObj, importedKeysObj) {
+    EnigmailLog.DEBUG(
+      "keyRing.jsm: EnigmailKeyRing.importKeyFromFile: fileName=" +
+        inputFile.path +
+        "\n"
+    );
 
     const cApi = EnigmailCryptoAPI();
     let res = cApi.sync(cApi.importKeyFromFile(inputFile));
     if (importedKeysObj) {
       importedKeysObj.value = res.importedKeys.join(";");
     }
 
-    if (!res) return 1;
+    if (!res) {
+      return 1;
+    }
 
     if (res.importedKeys.length > 0) {
       EnigmailKeyRing.updateKeys(res.importedKeys);
-    }
-    else if (res.importSum > res.importUnchanged) {
+    } else if (res.importSum > res.importUnchanged) {
       EnigmailKeyRing.clearCache();
     }
 
     return res.exitCode;
   },
 
-
   /**
    * empty the key cache, such that it will get loaded next time it is accessed
    *
    * no input or return values
    */
-  clearCache: function() {
+  clearCache() {
     EnigmailLog.DEBUG("keyRing.jsm: EnigmailKeyRing.clearCache\n");
     gKeyListObj = {
       keyList: [],
-      keySortList: []
+      keySortList: [],
     };
 
     gKeyIndex = [];
     gSubkeyIndex = [];
   },
 
   /**
    * Check if the cache is empty
    *
    * @return  Boolean: true: cache cleared
    */
-  getCacheEmpty: function() {
-    return (gKeyIndex.length === 0);
+  getCacheEmpty() {
+    return gKeyIndex.length === 0;
   },
 
   /**
    * Get a list of UserIds for a given key.
    * Only the Only UIDs with highest trust level are returned.
    *
    * @param  String  keyId   key, optionally preceeded with 0x
    *
    * @return Array of String: list of UserIds
    */
-  getValidUids: function(keyId) {
+  getValidUids(keyId) {
     let r = [];
     let keyObj = this.getKeyById(keyId);
 
     if (keyObj) {
       const TRUSTLEVELS_SORTED = EnigmailTrust.trustLevelsSorted();
       let hideInvalidUid = true;
       let maxTrustLevel = TRUSTLEVELS_SORTED.indexOf(keyObj.keyTrust);
 
       if (EnigmailTrust.isInvalid(keyObj.keyTrust)) {
         // pub key not valid (anymore)-> display all UID's
         hideInvalidUid = false;
       }
 
       for (let i in keyObj.userIds) {
         if (keyObj.userIds[i].type !== "uat") {
           if (hideInvalidUid) {
-            let thisTrust = TRUSTLEVELS_SORTED.indexOf(keyObj.userIds[i].keyTrust);
+            let thisTrust = TRUSTLEVELS_SORTED.indexOf(
+              keyObj.userIds[i].keyTrust
+            );
             if (thisTrust > maxTrustLevel) {
               r = [keyObj.userIds[i].userId];
               maxTrustLevel = thisTrust;
-            }
-            else if (thisTrust === maxTrustLevel) {
+            } else if (thisTrust === maxTrustLevel) {
               r.push(keyObj.userIds[i].userId);
             }
             // else do not add uid
-          }
-          else if (!EnigmailTrust.isInvalid(keyObj.userIds[i].keyTrust) || !hideInvalidUid) {
+          } else if (
+            !EnigmailTrust.isInvalid(keyObj.userIds[i].keyTrust) ||
+            !hideInvalidUid
+          ) {
             // UID valid  OR  key not valid, but invalid keys allowed
             r.push(keyObj.userIds[i].userId);
           }
         }
       }
     }
 
     return r;
@@ -386,48 +425,60 @@ var EnigmailKeyRing = {
    * @param userId            String   - space or comma separated list of keys to export. Specification by
    *                                     key ID, fingerprint, or userId
    * @param outputFile        String or nsIFile - output file name or Object - or NULL
    * @param exitCodeObj       Object   - o.value will contain exit code
    * @param errorMsgObj       Object   - o.value will contain error message from GnuPG
    *
    * @return String - if outputFile is NULL, the key block data; "" if a file is written
    */
-  extractKey: function(includeSecretKey, id, outputFile, exitCodeObj, errorMsgObj) {
+  extractKey(includeSecretKey, id, outputFile, exitCodeObj, errorMsgObj) {
     EnigmailLog.DEBUG("keyRing.jsm: EnigmailKeyRing.extractKey: " + id + "\n");
     exitCodeObj.value = -1;
 
-    console.debug("keyRing.jsm: EnigmailKeyRing.extractKey: type of parameter id:");
+    console.debug(
+      "keyRing.jsm: EnigmailKeyRing.extractKey: type of parameter id:"
+    );
     console.debug(typeof id);
     console.debug(id);
-    
+
     if (includeSecretKey) {
       throw new Error("extractKey with secret key not implemented");
     }
-    
+
     if (!id.length) {
-        return "";
+      return "";
     }
-    
+
     if (id.length > 1) {
-      throw new Error("keyRing.jsm: EnigmailKeyRing.extractKey: multiple IDs not yet implemented");
+      throw new Error(
+        "keyRing.jsm: EnigmailKeyRing.extractKey: multiple IDs not yet implemented"
+      );
     }
 
     const cApi = EnigmailCryptoAPI();
     let keyBlock = cApi.sync(cApi.getPublicKey(id[0]));
     if (!keyBlock) {
       errorMsgObj.value = EnigmailLocale.getString("failKeyExtract");
       return "";
     }
 
     exitCodeObj.value = 0;
     if (outputFile) {
-      if (!EnigmailFiles.writeFileContents(outputFile, keyBlock, DEFAULT_FILE_PERMS)) {
+      if (
+        !EnigmailFiles.writeFileContents(
+          outputFile,
+          keyBlock,
+          DEFAULT_FILE_PERMS
+        )
+      ) {
         exitCodeObj.value = -1;
-        errorMsgObj.value = EnigmailLocale.getString("fileWriteFailed", [outputFile]);
+        errorMsgObj.value = EnigmailLocale.getString("fileWriteFailed", [
+          outputFile,
+        ]);
       }
       return "";
     }
     return keyBlock;
   },
 
   /**
    * import key from provided key data (synchronous)
@@ -441,19 +492,39 @@ var EnigmailKeyRing = {
    * @param minimizeKey     Boolean  - [OPTIONAL] minimize key for importing
    * @param limitedUids     Array<String> - [OPTIONAL] restrict importing the key(s) to a given set of UIDs
    *
    * @return Integer -  exit code:
    *      ExitCode == 0  => success
    *      ExitCode > 0   => error
    *      ExitCode == -1 => Cancelled by user
    */
-  importKey: function(parent, isInteractive, keyBlock, keyId, errorMsgObj, importedKeysObj, minimizeKey = false, limitedUids = []) {
+  importKey(
+    parent,
+    isInteractive,
+    keyBlock,
+    keyId,
+    errorMsgObj,
+    importedKeysObj,
+    minimizeKey = false,
+    limitedUids = []
+  ) {
     const cApi = EnigmailCryptoAPI();
-    return cApi.sync(this.importKeyAsync(parent, isInteractive, keyBlock, keyId, errorMsgObj, importedKeysObj, minimizeKey, limitedUids));
+    return cApi.sync(
+      this.importKeyAsync(
+        parent,
+        isInteractive,
+        keyBlock,
+        keyId,
+        errorMsgObj,
+        importedKeysObj,
+        minimizeKey,
+        limitedUids
+      )
+    );
   },
 
   /**
    * import key from provided key data
    *
    * @param parent          nsIWindow
    * @param isInteractive   Boolean  - if true, display confirmation dialog
    * @param keyBlock        String   - data containing key
@@ -463,52 +534,78 @@ var EnigmailKeyRing = {
    * @param minimizeKey     Boolean  - [OPTIONAL] minimize key for importing
    * @param limitedUids     Array<String> - [OPTIONAL] restrict importing the key(s) to a given set of UIDs
    *
    * @return Integer -  exit code:
    *      ExitCode == 0  => success
    *      ExitCode > 0   => error
    *      ExitCode == -1 => Cancelled by user
    */
-  importKeyAsync: async function(parent, isInteractive, keyBlock, keyId, errorMsgObj, importedKeysObj, minimizeKey = false, limitedUids = []) {
-    EnigmailLog.DEBUG(`keyRing.jsm: EnigmailKeyRing.importKeyAsync('${keyId}', ${isInteractive}, ${minimizeKey})\n`);
+  async importKeyAsync(
+    parent,
+    isInteractive,
+    keyBlock,
+    keyId,
+    errorMsgObj,
+    importedKeysObj,
+    minimizeKey = false,
+    limitedUids = []
+  ) {
+    EnigmailLog.DEBUG(
+      `keyRing.jsm: EnigmailKeyRing.importKeyAsync('${keyId}', ${isInteractive}, ${minimizeKey})\n`
+    );
 
     const beginIndexObj = {};
     const endIndexObj = {};
-    const blockType = EnigmailArmor.locateArmoredBlock(keyBlock, 0, "", beginIndexObj, endIndexObj, {});
+    const blockType = EnigmailArmor.locateArmoredBlock(
+      keyBlock,
+      0,
+      "",
+      beginIndexObj,
+      endIndexObj,
+      {}
+    );
     if (!blockType) {
       errorMsgObj.value = EnigmailLocale.getString("noPGPblock");
       return 1;
     }
 
     if (blockType.search(/^(PUBLIC|PRIVATE) KEY BLOCK$/) !== 0) {
       errorMsgObj.value = EnigmailLocale.getString("notFirstBlock");
       return 1;
     }
 
-    const pgpBlock = keyBlock.substr(beginIndexObj.value,
-      endIndexObj.value - beginIndexObj.value + 1);
+    const pgpBlock = keyBlock.substr(
+      beginIndexObj.value,
+      endIndexObj.value - beginIndexObj.value + 1
+    );
 
     if (isInteractive) {
-      if (!(getDialog().confirmDlg(parent, EnigmailLocale.getString("importKeyConfirm"), EnigmailLocale.getString("keyMan.button.import")))) {
+      if (
+        !getDialog().confirmDlg(
+          parent,
+          EnigmailLocale.getString("importKeyConfirm"),
+          EnigmailLocale.getString("keyMan.button.import")
+        )
+      ) {
         errorMsgObj.value = EnigmailLocale.getString("failCancel");
         return -1;
       }
     }
 
     if (limitedUids.length > 0) {
       throw new Error("importKeyAsync with limitedUids: not implemented");
     }
 
     if (minimizeKey) {
       throw new Error("importKeyAsync with minimizeKey: not implemented");
     }
 
     const cApi = EnigmailCryptoAPI();
-    let result = cApi.sync(cApi.importKeyBlock(pgpBlock));
+    cApi.sync(cApi.importKeyBlock(pgpBlock));
 
     if (!importedKeysObj) {
       importedKeysObj = {};
     }
     importedKeysObj.value = [];
 
     let exitCode = 0;
 
@@ -529,40 +626,49 @@ var EnigmailKeyRing = {
    * @passphrase: String     - password; null if no password
    * @listener:   Object     - {
    *                             function onDataAvailable(data) {...},
    *                             function onStopRequest(exitCode) {...}
    *                           }
    *
    * @return: handle to process
    */
-  generateKey: function(name, comment, email, expiryDate, keyLength, keyType,
-    passphrase, listener) {
+  generateKey(
+    name,
+    comment,
+    email,
+    expiryDate,
+    keyLength,
+    keyType,
+    passphrase,
+    listener
+  ) {
     EnigmailLog.WRITE("keyRing.jsm: generateKey:\n");
     throw new Error("Not implemented");
   },
 
   /**
    * try to find valid key for encryption to passed email address
    *
    * @param details if not null returns error in details.msg
    *
    * @return: found key ID (without leading "0x") or null
    */
-  getValidKeyForRecipient: function(emailAddr, minTrustLevelIndex, details) {
-    EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient(): emailAddr=\"" + emailAddr + "\"\n");
+  getValidKeyForRecipient(emailAddr, minTrustLevelIndex, details) {
+    EnigmailLog.DEBUG(
+      'keyRing.jsm: getValidKeyForRecipient(): emailAddr="' + emailAddr + '"\n'
+    );
     const TRUSTLEVELS_SORTED = EnigmailTrust.trustLevelsSorted();
     const fullTrustIndex = TRUSTLEVELS_SORTED.indexOf("f");
 
     emailAddr = emailAddr.toLowerCase();
     var embeddedEmailAddr = "<" + emailAddr + ">";
 
     // note: we can't take just the first matched because we might have faked keys as duplicates
     var foundKeyId = null;
-    var foundTrustLevel = null;
     var foundKeyTrustIndex = null;
 
     let k = this.getAllKeys(null, "validity", -1);
     let keyList = k.keyList;
     let keySortList = k.keySortList;
 
     // **** LOOP to check against each key
     // - note: we have sorted the keys according to validity
@@ -575,42 +681,57 @@ var EnigmailKeyRing = {
 
       // key trust (our sort criterion) too low?
       // => *** regular END of the loop
       if (keyTrustIndex < minTrustLevelIndex) {
         if (!foundKeyId) {
           if (details) {
             details.msg = "ProblemNoKey";
           }
-          let msg = "no key with enough trust level for '" + emailAddr + "' found";
-          EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  " + msg + "\n");
+          let msg =
+            "no key with enough trust level for '" + emailAddr + "' found";
+          EnigmailLog.DEBUG(
+            "keyRing.jsm: getValidKeyForRecipient():  " + msg + "\n"
+          );
         }
         return foundKeyId; // **** regular END OF LOOP (return NULL or found single key)
       }
 
       // key valid for encryption?
-      if (keyObj.keyUseFor.indexOf("E") < 0) {
+      if (!keyObj.keyUseFor.includes("E")) {
         //EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  skip key " + keyObj.keyId + " (not provided for encryption)\n");
         continue; // not valid for encryption => **** CONTINUE the LOOP
       }
       // key disabled?
-      if (keyObj.keyUseFor.indexOf("D") >= 0) {
+      if (keyObj.keyUseFor.includes("D")) {
         //EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  skip key " + keyObj.keyId + " (disabled)\n");
         continue; // disabled => **** CONTINUE the LOOP
       }
 
       // check against the user ID
       var userId = keyObj.userId.toLowerCase();
-      if (userId && (userId == emailAddr || userId.indexOf(embeddedEmailAddr) >= 0)) {
+      if (
+        userId &&
+        (userId == emailAddr || userId.includes(embeddedEmailAddr))
+      ) {
         if (keyTrustIndex < minTrustLevelIndex) {
-          EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  matching key=" + keyObj.keyId + " found but not enough trust\n");
-        }
-        else {
+          EnigmailLog.DEBUG(
+            "keyRing.jsm: getValidKeyForRecipient():  matching key=" +
+              keyObj.keyId +
+              " found but not enough trust\n"
+          );
+        } else {
           // key with enough trust level found
-          EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  key=" + keyObj.keyId + " keyTrust=\"" + keyTrust + "\" found\n");
+          EnigmailLog.DEBUG(
+            "keyRing.jsm: getValidKeyForRecipient():  key=" +
+              keyObj.keyId +
+              ' keyTrust="' +
+              keyTrust +
+              '" found\n'
+          );
 
           // immediately return if a fully or ultimately trusted key is found
           // (faked keys should not be an issue here, so we don't have to check other keys)
           if (keyTrustIndex >= fullTrustIndex) {
             return keyObj.keyId;
           }
 
           if (foundKeyId != keyObj.keyId) {
@@ -620,19 +741,31 @@ var EnigmailKeyRing = {
               if (foundKeyTrustIndex > keyTrustIndex) {
                 return foundKeyId; // OK, previously found key has higher trust level
               }
               // error because we have two keys with same trust level
               // => let the user decide (to prevent from using faked keys with default trust level)
               if (details) {
                 details.msg = "ProblemMultipleKeys";
               }
-              let msg = "multiple matching keys with same trust level found for '" + emailAddr + "' ";
-              EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  " + msg +
-                " trustLevel=\"" + keyTrust + "\" (0x" + foundKeyId + " and 0x" + keyObj.keyId + ")\n");
+              let msg =
+                "multiple matching keys with same trust level found for '" +
+                emailAddr +
+                "' ";
+              EnigmailLog.DEBUG(
+                "keyRing.jsm: getValidKeyForRecipient():  " +
+                  msg +
+                  ' trustLevel="' +
+                  keyTrust +
+                  '" (0x' +
+                  foundKeyId +
+                  " and 0x" +
+                  keyObj.keyId +
+                  ")\n"
+              );
               return null;
             }
             // save found key to compare with other matching keys (handling of faked keys)
             foundKeyId = keyObj.keyId;
             foundKeyTrustIndex = keyTrustIndex;
           }
           continue; // matching key found (again) => **** CONTINUE the LOOP (don't check Sub-UserIDs)
         }
@@ -643,23 +776,35 @@ var EnigmailKeyRing = {
       // - Note: sub user IDs have NO owner trust
       for (var subUidIdx = 1; subUidIdx < keyObj.userIds.length; subUidIdx++) {
         var subUidObj = keyObj.userIds[subUidIdx];
         var subUserId = subUidObj.userId.toLowerCase();
         var subUidTrust = subUidObj.keyTrust;
         var subUidTrustIndex = TRUSTLEVELS_SORTED.indexOf(subUidTrust);
         //EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  check subUid " + subUidObj.keyId + "\n");
 
-        if (subUserId && (subUserId == emailAddr || subUserId.indexOf(embeddedEmailAddr) >= 0)) {
+        if (
+          subUserId &&
+          (subUserId == emailAddr || subUserId.includes(embeddedEmailAddr))
+        ) {
           if (subUidTrustIndex < minTrustLevelIndex) {
-            EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  matching subUid=" + keyObj.keyId + " found but not enough trust\n");
-          }
-          else {
+            EnigmailLog.DEBUG(
+              "keyRing.jsm: getValidKeyForRecipient():  matching subUid=" +
+                keyObj.keyId +
+                " found but not enough trust\n"
+            );
+          } else {
             // subkey with enough trust level found
-            EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  matching subUid in key=" + keyObj.keyId + " keyTrust=\"" + keyTrust + "\" found\n");
+            EnigmailLog.DEBUG(
+              "keyRing.jsm: getValidKeyForRecipient():  matching subUid in key=" +
+                keyObj.keyId +
+                ' keyTrust="' +
+                keyTrust +
+                '" found\n'
+            );
 
             if (keyTrustIndex >= fullTrustIndex) {
               // immediately return if a fully or ultimately trusted key is found
               // (faked keys should not be an issue here, so we don't have to check other keys)
               return keyObj.keyId;
             }
 
             if (foundKeyId != keyObj.keyId) {
@@ -669,33 +814,48 @@ var EnigmailKeyRing = {
                 if (foundKeyTrustIndex > subUidTrustIndex) {
                   return foundKeyId; // OK, previously found key has higher trust level
                 }
                 // error because we have two keys with same trust level
                 // => let the user decide (to prevent from using faked keys with default trust level)
                 if (details) {
                   details.msg = "ProblemMultipleKeys";
                 }
-                let msg = "multiple matching keys with same trust level found for '" + emailAddr + "' ";
-                EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  " + msg +
-                  " trustLevel=\"" + keyTrust + "\" (0x" + foundKeyId + " and 0x" + keyObj.keyId + ")\n");
+                let msg =
+                  "multiple matching keys with same trust level found for '" +
+                  emailAddr +
+                  "' ";
+                EnigmailLog.DEBUG(
+                  "keyRing.jsm: getValidKeyForRecipient():  " +
+                    msg +
+                    ' trustLevel="' +
+                    keyTrust +
+                    '" (0x' +
+                    foundKeyId +
+                    " and 0x" +
+                    keyObj.keyId +
+                    ")\n"
+                );
                 return null;
               }
               // save found key to compare with other matching keys (handling of faked keys)
               foundKeyId = keyObj.keyId;
               foundKeyTrustIndex = subUidTrustIndex;
             }
           }
         }
       }
-
     } // **** LOOP to check against each key
 
     if (!foundKeyId) {
-      EnigmailLog.DEBUG("keyRing.jsm: getValidKeyForRecipient():  no key for '" + emailAddr + "' found\n");
+      EnigmailLog.DEBUG(
+        "keyRing.jsm: getValidKeyForRecipient():  no key for '" +
+          emailAddr +
+          "' found\n"
+      );
     }
     return foundKeyId;
   },
 
   /**
    *  Determine the key ID for a set of given addresses
    *
    * @param {Array<String>} addresses: email addresses
@@ -705,83 +865,97 @@ var EnigmailKeyRing = {
    *                                       * addr {String}: email addresses
    *                                       * msg {String}:  related error
    *                                       }
    *                                   - keyMap {Object<String>}: map of email addr -> keyID
    * @param {Array<String>} resultingArray: list of found key IDs
    *
    * @return {Boolean}: true if at least one key missing; false otherwise
    */
-  getValidKeysForAllRecipients: function(addresses, minTrustLevel, details, resultingArray) {
-
+  getValidKeysForAllRecipients(
+    addresses,
+    minTrustLevel,
+    details,
+    resultingArray
+  ) {
     let minTrustLevelIndex = TRUSTLEVELS_SORTED.indexOf(minTrustLevel);
 
     // check whether each address is or has a key:
     let keyMissing = false;
     if (details) {
       details.errArray = [];
       details.keyMap = {};
     }
     for (let i = 0; i < addresses.length; i++) {
       let addr = addresses[i];
       // try to find current address in key list:
       let keyId = null;
       var errMsg = null;
-      if (addr.indexOf('@') >= 0) {
+      if (addr.includes("@")) {
         // try email match:
         var addrErrDetails = {};
-        let foundKeyId = this.getValidKeyForRecipient(addr, minTrustLevelIndex, addrErrDetails);
+        let foundKeyId = this.getValidKeyForRecipient(
+          addr,
+          minTrustLevelIndex,
+          addrErrDetails
+        );
         if (details && addrErrDetails.msg) {
           errMsg = addrErrDetails.msg;
         }
         if (foundKeyId) {
           keyId = "0x" + foundKeyId.toUpperCase();
           resultingArray.push(keyId);
         }
-      }
-      else {
+      } else {
         // try key match:
         var keyObj = this.getKeyById(addr);
 
         if (keyObj) {
           // if found, check whether the trust level is enough
-          if (TRUSTLEVELS_SORTED.indexOf(keyObj.keyTrust) >= minTrustLevelIndex) {
+          if (
+            TRUSTLEVELS_SORTED.indexOf(keyObj.keyTrust) >= minTrustLevelIndex
+          ) {
             keyId = "0x" + keyObj.keyId.toUpperCase();
             resultingArray.push(keyId);
           }
         }
       }
 
       if (keyId) {
         if (details) {
           details.keyMap[addr.toLowerCase()] = keyId;
         }
-      }
-      else {
+      } else {
         // no key for this address found
         keyMissing = true;
         if (details) {
           if (!errMsg) {
             errMsg = "ProblemNoKey";
           }
           var detailsElem = {};
           detailsElem.addr = addr;
           detailsElem.msg = errMsg;
           details.errArray.push(detailsElem);
         }
-        EnigmailLog.DEBUG("keyRing.jsm: doValidKeysForAllRecipients(): return null (no single valid key found for=\"" + addr + "\" with minTrustLevel=\"" + minTrustLevel + "\")\n");
+        EnigmailLog.DEBUG(
+          'keyRing.jsm: doValidKeysForAllRecipients(): return null (no single valid key found for="' +
+            addr +
+            '" with minTrustLevel="' +
+            minTrustLevel +
+            '")\n'
+        );
       }
     }
     return keyMissing;
   },
 
   /**
    * Rebuild the quick access search indexes after the key list was loaded
    */
-  rebuildKeyIndex: function() {
+  rebuildKeyIndex() {
     gKeyIndex = [];
     gSubkeyIndex = [];
 
     for (let i in gKeyListObj.keyList) {
       let k = gKeyListObj.keyList[i];
       gKeyIndex[k.keyId] = k;
       gKeyIndex[k.fpr] = k;
       gKeyIndex[k.keyId.substr(-8, 8)] = k;
@@ -794,87 +968,106 @@ var EnigmailKeyRing = {
   },
 
   /**
    * Update specific keys in the key cache. If the key objects don't exist yet,
    * they will be created
    *
    * @param keys: Array of String - key IDs or fingerprints
    */
-  updateKeys: function(keys) {
+  updateKeys(keys) {
     EnigmailLog.DEBUG("keyRing.jsm: updateKeys(" + keys.join(",") + ")\n");
     let uniqueKeys = [...new Set(keys)]; // make key IDs unique
 
     deleteKeysFromCache(uniqueKeys);
 
     if (gKeyListObj.keyList.length > 0) {
       loadKeyList(null, null, 1, uniqueKeys);
-    }
-    else {
+    } else {
       loadKeyList(null, null, 1);
     }
 
     getWindows().keyManReloadKeys();
-  }
+  },
 }; //  EnigmailKeyRing
 
-
 /************************ INTERNAL FUNCTIONS ************************/
 
 function sortByUserId(keyListObj, sortDirection) {
   return function(a, b) {
-    return (a.userId < b.userId) ? -sortDirection : sortDirection;
+    return a.userId < b.userId ? -sortDirection : sortDirection;
   };
 }
 
 const sortFunctions = {
-  keyid: function(keyListObj, sortDirection) {
+  keyid(keyListObj, sortDirection) {
     return function(a, b) {
-      return (a.keyId < b.keyId) ? -sortDirection : sortDirection;
+      return a.keyId < b.keyId ? -sortDirection : sortDirection;
+    };
+  },
+
+  keyidshort(keyListObj, sortDirection) {
+    return function(a, b) {
+      return a.keyId.substr(-8, 8) < b.keyId.substr(-8, 8)
+        ? -sortDirection
+        : sortDirection;
     };
   },
 
-  keyidshort: function(keyListObj, sortDirection) {
+  fpr(keyListObj, sortDirection) {
     return function(a, b) {
-      return (a.keyId.substr(-8, 8) < b.keyId.substr(-8, 8)) ? -sortDirection : sortDirection;
+      return keyListObj.keyList[a.keyNum].fpr < keyListObj.keyList[b.keyNum].fpr
+        ? -sortDirection
+        : sortDirection;
     };
   },
 
-  fpr: function(keyListObj, sortDirection) {
+  keytype(keyListObj, sortDirection) {
     return function(a, b) {
-      return (keyListObj.keyList[a.keyNum].fpr < keyListObj.keyList[b.keyNum].fpr) ? -sortDirection : sortDirection;
+      return keyListObj.keyList[a.keyNum].secretAvailable <
+        keyListObj.keyList[b.keyNum].secretAvailable
+        ? -sortDirection
+        : sortDirection;
     };
   },
 
-  keytype: function(keyListObj, sortDirection) {
+  validity(keyListObj, sortDirection) {
     return function(a, b) {
-      return (keyListObj.keyList[a.keyNum].secretAvailable < keyListObj.keyList[b.keyNum].secretAvailable) ? -sortDirection : sortDirection;
-    };
-  },
-
-  validity: function(keyListObj, sortDirection) {
-    return function(a, b) {
-      return (EnigmailTrust.trustLevelsSorted().indexOf(EnigmailTrust.getTrustCode(keyListObj.keyList[a.keyNum])) < EnigmailTrust.trustLevelsSorted().indexOf(EnigmailTrust.getTrustCode(
-        keyListObj.keyList[b.keyNum]))) ? -sortDirection : sortDirection;
+      return EnigmailTrust.trustLevelsSorted().indexOf(
+        EnigmailTrust.getTrustCode(keyListObj.keyList[a.keyNum])
+      ) <
+        EnigmailTrust.trustLevelsSorted().indexOf(
+          EnigmailTrust.getTrustCode(keyListObj.keyList[b.keyNum])
+        )
+        ? -sortDirection
+        : sortDirection;
     };
   },
 
-  trust: function(keyListObj, sortDirection) {
+  trust(keyListObj, sortDirection) {
     return function(a, b) {
-      return (EnigmailTrust.trustLevelsSorted().indexOf(keyListObj.keyList[a.keyNum].ownerTrust) < EnigmailTrust.trustLevelsSorted().indexOf(keyListObj.keyList[b.keyNum].ownerTrust)) ?
-        -
-        sortDirection : sortDirection;
+      return EnigmailTrust.trustLevelsSorted().indexOf(
+        keyListObj.keyList[a.keyNum].ownerTrust
+      ) <
+        EnigmailTrust.trustLevelsSorted().indexOf(
+          keyListObj.keyList[b.keyNum].ownerTrust
+        )
+        ? -sortDirection
+        : sortDirection;
     };
   },
 
-  expiry: function(keyListObj, sortDirection) {
+  expiry(keyListObj, sortDirection) {
     return function(a, b) {
-      return (keyListObj.keyList[a.keyNum].expiryTime < keyListObj.keyList[b.keyNum].expiryTime) ? -sortDirection : sortDirection;
+      return keyListObj.keyList[a.keyNum].expiryTime <
+        keyListObj.keyList[b.keyNum].expiryTime
+        ? -sortDirection
+        : sortDirection;
     };
-  }
+  },
 };
 
 function getSortFunction(type, keyListObj, sortDirection) {
   return (sortFunctions[type] || sortByUserId)(keyListObj, sortDirection);
 }
 
 /**
  * Load the key list into memory and return it sorted by a specified column
@@ -894,30 +1087,34 @@ function loadKeyList(win, sortColumn, so
   if (gLoadingKeys) {
     waitForKeyList();
     return;
   }
   gLoadingKeys = true;
 
   try {
     const cApi = EnigmailCryptoAPI();
-    cApi.getKeys(onlyKeys)
+    cApi
+      .getKeys(onlyKeys)
       .then(keyList => {
-        createAndSortKeyList(keyList, sortColumn, sortDirection, onlyKeys === null);
+        createAndSortKeyList(
+          keyList,
+          sortColumn,
+          sortDirection,
+          onlyKeys === null
+        );
         gLoadingKeys = false;
-
       })
       .catch(e => {
         EnigmailLog.ERROR(`keyRing.jsm: loadKeyList: error ${e}
 `);
         gLoadingKeys = false;
       });
     waitForKeyList();
-  }
-  catch (ex) {
+  } catch (ex) {
     EnigmailLog.ERROR("keyRing.jsm: loadKeyList: exception: " + ex.toString());
   }
 }
 
 /**
  * Update the global key sort-list (quick index to keys)
  *
  * no return value
@@ -925,34 +1122,34 @@ function loadKeyList(win, sortColumn, so
 function updateSortList() {
   gKeyListObj.keySortList = [];
   for (let i = 0; i < gKeyListObj.keyList.length; i++) {
     let keyObj = gKeyListObj.keyList[i];
     gKeyListObj.keySortList.push({
       userId: keyObj.userId.toLowerCase(),
       keyId: keyObj.keyId,
       fpr: keyObj.fpr,
-      keyNum: i
+      keyNum: i,
     });
   }
-
 }
 
-
 /**
  * Delete a set of keys from the key cache. Does not rebuild key indexes.
  * Not found keys are skipped.
  *
  * @param keyList: Array of Strings: key IDs (or fpr) to delete
  *
  * @return Array of deleted key objects
  */
 
 function deleteKeysFromCache(keyList) {
-  EnigmailLog.DEBUG("keyRing.jsm: deleteKeysFromCache(" + keyList.join(",") + ")\n");
+  EnigmailLog.DEBUG(
+    "keyRing.jsm: deleteKeysFromCache(" + keyList.join(",") + ")\n"
+  );
 
   let deleted = [];
   let foundKeys = [];
   for (let keyId of keyList) {
     let k = EnigmailKeyRing.getKeyById(keyId, true);
     if (k) {
       foundKeys.push(k);
     }
@@ -970,67 +1167,82 @@ function deleteKeysFromCache(keyList) {
       gKeyListObj.keyList.splice(foundIndex, 1);
       deleted.push(k);
     }
   }
 
   return deleted;
 }
 
-function createAndSortKeyList(keyList, sortColumn, sortDirection, resetKeyCache) {
+function createAndSortKeyList(
+  keyList,
+  sortColumn,
+  sortDirection,
+  resetKeyCache
+) {
   EnigmailLog.DEBUG("keyRing.jsm: createAndSortKeyList()\n");
 
-  if (typeof sortColumn !== "string")
+  if (typeof sortColumn !== "string") {
     sortColumn = "userid";
-  if (!sortDirection)
+  }
+  if (!sortDirection) {
     sortDirection = 1;
+  }
 
-  if ((!("keyList" in gKeyListObj)) || (resetKeyCache)) {
+  if (!("keyList" in gKeyListObj) || resetKeyCache) {
     gKeyListObj.keyList = [];
     gKeyListObj.keySortList = [];
     gKeyListObj.trustModel = "?";
   }
 
-  gKeyListObj.keyList = gKeyListObj.keyList.concat(keyList.map(k => {
-    return newEnigmailKeyObj(k);
-  }));
+  gKeyListObj.keyList = gKeyListObj.keyList.concat(
+    keyList.map(k => {
+      return newEnigmailKeyObj(k);
+    })
+  );
 
   // update the quick index for sorting keys
   updateSortList();
 
   // create a hash-index on key ID (8 and 16 characters and fingerprint)
   // in a single array
 
   EnigmailKeyRing.rebuildKeyIndex();
 
-  gKeyListObj.keySortList.sort(getSortFunction(sortColumn.toLowerCase(), gKeyListObj, sortDirection));
+  gKeyListObj.keySortList.sort(
+    getSortFunction(sortColumn.toLowerCase(), gKeyListObj, sortDirection)
+  );
 }
 
-
+/*
 function runKeyUsabilityCheck() {
   EnigmailLog.DEBUG("keyRing.jsm: runKeyUsabilityCheck()\n");
 
-  EnigmailTimer.setTimeout(function _f() {
+  EnigmailTimer.setTimeout(function() {
     try {
       let msg = getKeyUsability().keyExpiryCheck();
 
       if (msg && msg.length > 0) {
         getDialog().info(null, msg);
-      }
-      else {
+      } else {
         getKeyUsability().checkOwnertrust();
       }
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "keyRing.jsm: runKeyUsabilityCheck: exception " +
+          ex.message +
+          "\n" +
+          ex.stack +
+          "\n"
+      );
     }
-    catch (ex) {
-      EnigmailLog.DEBUG("keyRing.jsm: runKeyUsabilityCheck: exception " + ex.message + "\n" + ex.stack + "\n");
-    }
-
   }, 60 * 1000); // 1 minute
 }
+*/
 
 function waitForKeyList() {
   let mainThread = Services.tm.mainThread;
-  while (gLoadingKeys)
+  while (gLoadingKeys) {
     mainThread.processNextEvent(true);
+  }
 }
 
-
 EnigmailKeyRing.clearCache();
--- a/mail/extensions/openpgp/content/modules/keyUsability.jsm
+++ b/mail/extensions/openpgp/content/modules/keyUsability.jsm
@@ -1,329 +1,374 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailKeyUsability"];
 
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
 
 const getDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
-const getWindows = EnigmailLazy.loader("enigmail/windows.jsm", "EnigmailWindows");
-const getKeyRing = EnigmailLazy.loader("enigmail/keyRing.jsm", "EnigmailKeyRing");
+const getWindows = EnigmailLazy.loader(
+  "enigmail/windows.jsm",
+  "EnigmailWindows"
+);
+const getKeyRing = EnigmailLazy.loader(
+  "enigmail/keyRing.jsm",
+  "EnigmailKeyRing"
+);
 
 const DAY = 86400; // number of seconds of 1 day
 
 var EnigmailKeyUsability = {
   /**
    * Check whether some key pairs expire in less than N days from now.
    *
    * @param keySpecArr  - Array: list of key IDs or User IDs
    * @param numDay      - Number: number of days from now
    *
    * @return Array      - list of keys that will expire
    */
 
-  getExpiryForKeySpec: function(keySpecArr, numDays) {
+  getExpiryForKeySpec(keySpecArr, numDays) {
     EnigmailLog.DEBUG("keyUsability.jsm: getExpiryForKeySpec()\n");
     let now = Math.floor(Date.now() / 1000);
     let enigmailSvc = EnigmailCore.getService();
-    if (!enigmailSvc) return [];
+    if (!enigmailSvc) {
+      return [];
+    }
 
     let result = keySpecArr.reduce(function(p, keySpec) {
       let key;
 
       if (keySpec.search(/^(0x)?[0-9A-F]{8,40}$/i) === 0) {
         key = getKeyRing().getKeyById(keySpec);
-      }
-      else {
+      } else {
         key = getKeyRing().getSecretKeyByEmail(keySpec);
       }
-      if (!key) return p;
+      if (!key) {
+        return p;
+      }
 
       let maxExpiry = Number.MIN_VALUE;
       let maxKey = null;
 
       let ex = key.getKeyExpiry();
       if (ex > maxExpiry) {
         maxExpiry = ex;
         maxKey = key;
       }
 
-      if (maxExpiry < now + (DAY * numDays) && maxExpiry >= now) p.push(maxKey);
+      if (maxExpiry < now + DAY * numDays && maxExpiry >= now) {
+        p.push(maxKey);
+      }
 
       return p;
     }, []);
 
     result = uniqueKeyList(result);
     return result;
   },
 
   /**
    * Determine the configured key specifications for all identities
    * where Enigmail is enabled
    *
    * @return  Array of Strings - list of keyId and email addresses
    */
-  getKeysSpecForIdentities: function() {
+  getKeysSpecForIdentities() {
     EnigmailLog.DEBUG("keyUsability.jsm: getKeysSpecForIdentities()\n");
-    let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+    let accountManager = Cc[
+      "@mozilla.org/messenger/account-manager;1"
+    ].getService(Ci.nsIMsgAccountManager);
 
     let keySpecList = [];
 
     for (let acct = 0; acct < accountManager.accounts.length; acct++) {
       let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);
 
       for (let i = 0; i < ac.identities.length; i++) {
         let id = ac.identities.queryElementAt(i, Ci.nsIMsgIdentity);
         if (id.getBoolAttribute("enablePgp")) {
           if (id.getIntAttribute("pgpKeyMode") === 1) {
             keySpecList.push(id.getCharAttribute("pgpkeyId"));
-          }
-          else {
+          } else {
             keySpecList.push(id.email);
           }
         }
       }
     }
 
     return keySpecList;
   },
 
   /**
    * Check if all keys of all configured identities are still valid in N days.
    * (N is configured via warnKeyExpiryNumDays; 0 = disable the check)
    *
    * @return  Array of keys - the keys that have expired since the last check
    *          null in case no check was performed
    */
-  getNewlyExpiredKeys: function() {
+  getNewlyExpiredKeys() {
     EnigmailLog.DEBUG("keyUsability.jsm: getNewlyExpiredKeys()\n");
 
     let numDays = EnigmailPrefs.getPref("warnKeyExpiryNumDays");
-    if (numDays < 1) return null;
+    if (numDays < 1) {
+      return null;
+    }
 
     let now = Date.now();
 
     let lastResult = {
       expiredList: [],
-      lastCheck: 0
+      lastCheck: 0,
     };
 
     let lastRes = EnigmailPrefs.getPref("keyCheckResult");
     if (lastRes.length > 0) {
       lastResult = JSON.parse(lastRes);
     }
 
-    if (now - lastResult.lastCheck < DAY * 1000) return null;
+    if (now - lastResult.lastCheck < DAY * 1000) {
+      return null;
+    }
 
     let keys = this.getKeysSpecForIdentities();
 
     if (keys.length === 0) {
       lastResult.lastCheck = now;
       EnigmailPrefs.setPref("keyCheckResult", JSON.stringify(lastResult));
       return [];
     }
 
     let expired = this.getExpiryForKeySpec(keys, numDays);
 
-    let expiredList = expired.reduce(function _f(p, key) {
+    let expiredList = expired.reduce(function(p, key) {
       p.push(key.keyId);
       return p;
     }, []);
 
     let newResult = {
-      expiredList: expiredList,
-      lastCheck: now
+      expiredList,
+      lastCheck: now,
     };
 
     EnigmailPrefs.setPref("keyCheckResult", JSON.stringify(newResult));
 
-    let warnList = expired.reduce(function _f(p, key) {
-      if (lastResult.expiredList.indexOf(key.keyId) < 0) {
+    let warnList = expired.reduce(function(p, key) {
+      if (!lastResult.expiredList.includes(key.keyId)) {
         p.push(key);
       }
       return p;
     }, []);
 
     return warnList;
   },
 
-  keyExpiryCheck: function() {
+  keyExpiryCheck() {
     EnigmailLog.DEBUG("keyUsability.jsm: keyExpiryCheck()\n");
 
     let expiredKeys = this.getNewlyExpiredKeys();
-    if (!expiredKeys || expiredKeys.length === 0) return "";
+    if (!expiredKeys || expiredKeys.length === 0) {
+      return "";
+    }
 
     let numDays = EnigmailPrefs.getPref("warnKeyExpiryNumDays");
 
     if (expiredKeys.length === 1) {
-      return EnigmailLocale.getString("expiry.keyExpiresSoon", [getKeyDesc(expiredKeys[0]), numDays]);
+      return EnigmailLocale.getString("expiry.keyExpiresSoon", [
+        getKeyDesc(expiredKeys[0]),
+        numDays,
+      ]);
     }
-    else {
-      let keyDesc = "";
-      for (let i = 0; i < expiredKeys.length; i++) {
-        keyDesc += "- " + getKeyDesc(expiredKeys[i]) + "\n";
-      }
-      return EnigmailLocale.getString("expiry.keysExpireSoon", [numDays, keyDesc]);
+
+    let keyDesc = "";
+    for (let i = 0; i < expiredKeys.length; i++) {
+      keyDesc += "- " + getKeyDesc(expiredKeys[i]) + "\n";
     }
+    return EnigmailLocale.getString("expiry.keysExpireSoon", [
+      numDays,
+      keyDesc,
+    ]);
   },
 
-
   /**
    * Check whether some key pairs (i.e. key with a secret key) have an
    * ownertrust of less than "ultimate".
    *
    * @param keySpecArr  - Array: list of key IDs or User IDs
    *
    * @return Array      - list of keys that have ownertrust below "ultimate"
    */
 
-  getOwnerTrustForKeySpec: function(keySpecArr) {
+  getOwnerTrustForKeySpec(keySpecArr) {
     EnigmailLog.DEBUG("keyUsability.jsm: getOwnerTrustForKeySpec()\n");
     let enigmailSvc = EnigmailCore.getService();
-    if (!enigmailSvc) return [];
+    if (!enigmailSvc) {
+      return [];
+    }
 
     let result = keySpecArr.reduce(function(p, keySpec) {
       let key;
 
       if (keySpec.search(/^(0x)?[0-9A-F]{8,40}$/i) === 0) {
         key = getKeyRing().getKeyById(keySpec);
-        if (!key) return p;
-      }
-      else {
+        if (!key) {
+          return p;
+        }
+      } else {
         key = getKeyRing().getSecretKeyByEmail(keySpec);
-        if (!key) return p;
+        if (!key) {
+          return p;
+        }
       }
 
       let ot = key.ownerTrust;
-      if (ot !== "u") p.push(key);
+      if (ot !== "u") {
+        p.push(key);
+      }
 
       return p;
     }, []);
 
     result = uniqueKeyList(result);
     return result;
   },
 
-
   /**
    * Check if all keys of all configured identities have "ultimate" ownertrust
    *
    * @return  String Message listing the keys that have less ownertrust
    *          resultObj.Count: Number of those keys
    *          resultObj.KeyId: KeyId (only if a single key is concerned)
    */
 
-  keyOwnerTrustCheck: function(resultObj) {
+  keyOwnerTrustCheck(resultObj) {
     EnigmailLog.DEBUG("keyUsability.jsm: keyOwnerTrustCheck()\n");
     resultObj.Count = 0;
 
     let keys = this.getKeysSpecForIdentities();
 
     if (keys.length === 0) {
       return "";
     }
 
     let keysMissingOwnertrust = this.getOwnerTrustForKeySpec(keys);
 
-    if (!keysMissingOwnertrust || keysMissingOwnertrust.length === 0) return "";
+    if (!keysMissingOwnertrust || keysMissingOwnertrust.length === 0) {
+      return "";
+    }
 
     resultObj.Count = keysMissingOwnertrust.length;
 
     if (keysMissingOwnertrust.length === 1) {
       let keyDesc = getKeyDesc(keysMissingOwnertrust[0]);
       resultObj.keyId = keysMissingOwnertrust[0].keyId;
       return EnigmailLocale.getString("expiry.keyMissingOwnerTrust", keyDesc);
     }
-    else {
-      let keyDesc = "";
-      for (let i = 0; i < keysMissingOwnertrust.length; i++) {
-        keyDesc += "- " + getKeyDesc(keysMissingOwnertrust[i]) + "\n";
-      }
-      return EnigmailLocale.getString("expiry.keysMissingOwnerTrust", keyDesc);
+
+    let keyDesc = "";
+    for (let i = 0; i < keysMissingOwnertrust.length; i++) {
+      keyDesc += "- " + getKeyDesc(keysMissingOwnertrust[i]) + "\n";
     }
+    return EnigmailLocale.getString("expiry.keysMissingOwnerTrust", keyDesc);
   },
 
   /**
    * Run the check for Ownertrust ("You rely on certifications") and
    * Display a message if something needs to be done
    */
-  checkOwnertrust: function() {
+  checkOwnertrust() {
     EnigmailLog.DEBUG("keyUsability.jsm: checkOwnertrust\n");
 
     var resultObj = {};
     let msg = this.keyOwnerTrustCheck(resultObj);
 
-    if (msg && (msg.length > 0) && EnigmailPrefs.getPref("warnOnMissingOwnerTrust")) {
+    if (
+      msg &&
+      msg.length > 0 &&
+      EnigmailPrefs.getPref("warnOnMissingOwnerTrust")
+    ) {
       let actionButtonText = "";
 
       if (resultObj && resultObj.Count === 1) {
         // single key is concerned
         actionButtonText = EnigmailLocale.getString("expiry.OpenKeyProperties");
-      }
-      else {
+      } else {
         // Multiple keys concerned
         actionButtonText = EnigmailLocale.getString("expiry.OpenKeyManager");
       }
 
       let checkedObj = {};
-      let r = getDialog().msgBox(null, {
+      let r = getDialog().msgBox(
+        null,
+        {
           msgtext: msg,
           dialogTitle: EnigmailLocale.getString("enigInfo"),
           checkboxLabel: EnigmailLocale.getString("dlgNoPrompt"),
           button1: EnigmailLocale.getString("dlg.button.close"),
           button2: actionButtonText,
-          iconType: EnigmailConstants.ICONTYPE_INFO
+          iconType: EnigmailConstants.ICONTYPE_INFO,
         },
-        checkedObj);
+        checkedObj
+      );
       if (r >= 0 && checkedObj.value) {
         // Do not show me this dialog again
         EnigmailPrefs.setPref("warnOnMissingOwnerTrust", false);
       }
       if (r == 1) {
         if (resultObj && resultObj.Count === 1) {
           // single key is concerned, open key details dialog
           getWindows().openKeyDetails(null, resultObj.keyId, false);
-        }
-        else {
+        } else {
           // Multiple keys concerned, open Key Manager
           getWindows().openKeyManager(null);
         }
       }
     }
-  }
+  },
 };
 
 /**
  * Remove duplicate key Object elements from an array
  *
  * @param arr - Array of key Objects to be worked on
  *
  * @return Array - the array without duplicates
  */
 
 function uniqueKeyList(arr) {
   return arr.reduce(function(p, c) {
-
-    let r = p.find(function _f(e, i, a) {
+    let r = p.find(function(e, i, a) {
       return e.keyId === c.keyId;
     });
 
-    if (r === undefined) p.push(c);
+    if (r === undefined) {
+      p.push(c);
+    }
     return p;
   }, []);
 }
 
-
 function getKeyDesc(key) {
-  return '"' + key.userId + '" (key ID ' + key.fprFormatted + ')';
+  return '"' + key.userId + '" (key ID ' + key.fprFormatted + ")";
 }
--- a/mail/extensions/openpgp/content/modules/keyserver.jsm
+++ b/mail/extensions/openpgp/content/modules/keyserver.jsm
@@ -3,49 +3,66 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailKeyServer"];
 
-Components.utils.importGlobalProperties(["XMLHttpRequest"]);
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailKeyserverURIs = ChromeUtils.import("chrome://openpgp/content/modules/keyserverUris.jsm").EnigmailKeyserverURIs;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailHttpProxy = ChromeUtils.import("chrome://openpgp/content/modules/httpProxy.jsm").EnigmailHttpProxy;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-const EnigmailXhrUtils = ChromeUtils.import("chrome://openpgp/content/modules/xhrUtils.jsm").EnigmailXhrUtils;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
-
-const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailKeyserverURIs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyserverUris.jsm"
+).EnigmailKeyserverURIs;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailGpg = ChromeUtils.import(
+  "chrome://openpgp/content/modules/gpg.jsm"
+).EnigmailGpg;
+const EnigmailXhrUtils = ChromeUtils.import(
+  "chrome://openpgp/content/modules/xhrUtils.jsm"
+).EnigmailXhrUtils;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 const ENIG_DEFAULT_HKP_PORT = "11371";
 const ENIG_DEFAULT_HKPS_PORT = "443";
 const ENIG_DEFAULT_LDAP_PORT = "389";
 
 const SKS_CACERT_URL = "https://sks-keyservers.net/sks-keyservers.netCA.pem";
 const HKPS_POOL_HOST = "hkps.pool.sks-keyservers.net";
-const SKS_CACERT_SUBJECTNAME = "CN=sks-keyservers.net CA,O=sks-keyservers.net CA,ST=Oslo,C=NO";
+const SKS_CACERT_SUBJECTNAME =
+  "CN=sks-keyservers.net CA,O=sks-keyservers.net CA,ST=Oslo,C=NO";
 
 /**
  KeySrvListener API
  Object implementing:
   - onProgress: function(percentComplete) [only implemented for download()]
   - onCancel: function() - the body will be set by the callee
 */
 
-
 function createError(errId) {
   let msg = "";
   switch (errId) {
     case EnigmailConstants.KEYSERVER_ERR_ABORTED:
       msg = EnigmailLocale.getString("keyserver.error.aborted");
       break;
     case EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR:
       msg = EnigmailLocale.getString("keyserver.error.serverError");
@@ -64,41 +81,40 @@ function createError(errId) {
       break;
     case EnigmailConstants.KEYSERVER_ERR_UNKNOWN:
       msg = EnigmailLocale.getString("keyserver.error.unknown");
       break;
   }
 
   return {
     result: errId,
-    errorDetails: msg
+    errorDetails: msg,
   };
 }
 
 /**
  * parse a keyserver specification and return host, protocol and port
  *
  * @param keyserver: String - name of keyserver with optional protocol and port.
  *                       E.g. keys.gnupg.net, hkps://keys.gnupg.net:443
  *
  * @return Object: {port, host, protocol} (all Strings)
  */
 function parseKeyserverUrl(keyserver) {
   if (keyserver.length > 1024) {
     // insane length of keyserver is forbidden
-    throw Components.results.NS_ERROR_FAILURE;
+    throw Cr.NS_ERROR_FAILURE;
   }
 
   keyserver = keyserver.toLowerCase().trim();
   let protocol = "";
   if (keyserver.search(/^[a-zA-Z0-9_.-]+:\/\//) === 0) {
     protocol = keyserver.replace(/^([a-zA-Z0-9_.-]+)(:\/\/.*)/, "$1");
     keyserver = keyserver.replace(/^[a-zA-Z0-9_.-]+:\/\//, "");
-  }
-  else {
+  } else {
     protocol = "hkp";
   }
 
   let port = "";
   switch (protocol) {
     case "hkp":
       port = ENIG_DEFAULT_HKP_PORT;
       break;
@@ -122,39 +138,40 @@ function parseKeyserverUrl(keyserver) {
     port = ENIG_DEFAULT_HKPS_PORT;
   }
   if (keyserver.search(/^(keybase\.io)$/) === 0) {
     protocol = "keybase";
     port = ENIG_DEFAULT_HKPS_PORT;
   }
 
   return {
-    protocol: protocol,
+    protocol,
     host: keyserver,
-    port: port
+    port,
   };
 }
 
-
 /**
  Object to handle HKP/HKPS requests via builtin XMLHttpRequest()
  */
 const accessHkpInternal = {
   /**
    * Create the payload of hkp requests (upload only)
    *
    */
-  buildHkpPayload: function(actionFlag, searchTerms) {
+  buildHkpPayload(actionFlag, searchTerms) {
     let payLoad = null,
       keyData = "";
 
     switch (actionFlag) {
       case EnigmailConstants.UPLOAD_KEY:
         keyData = EnigmailKeyRing.extractKey(false, searchTerms, null, {}, {});
-        if (keyData.length === 0) return null;
+        if (keyData.length === 0) {
+          return null;
+        }
 
         payLoad = "keytext=" + encodeURIComponent(keyData);
         return payLoad;
 
       case EnigmailConstants.DOWNLOAD_KEY:
       case EnigmailConstants.SEARCH_KEY:
       case EnigmailConstants.GET_SKS_CACERT:
         return "";
@@ -162,78 +179,83 @@ const accessHkpInternal = {
 
     // other actions are not yet implemented
     return null;
   },
 
   /**
    * return the URL and the HTTP access method for a given action
    */
-  createRequestUrl: function(keyserver, actionFlag, searchTerm) {
+  createRequestUrl(keyserver, actionFlag, searchTerm) {
     let keySrv = parseKeyserverUrl(keyserver);
 
     let method = "GET";
     let protocol;
 
     switch (keySrv.protocol) {
       case "hkp":
         protocol = "http";
         break;
       case "ldap":
-        throw Components.results.NS_ERROR_FAILURE;
-      default: // equals to hkps
+        throw Cr.NS_ERROR_FAILURE;
+      default:
+        // equals to hkps
         protocol = "https";
     }
 
     let url = protocol + "://" + keySrv.host + ":" + keySrv.port;
 
     if (actionFlag === EnigmailConstants.UPLOAD_KEY) {
       url += "/pks/add";
       method = "POST";
-    }
-    else if (actionFlag === EnigmailConstants.DOWNLOAD_KEY) {
+    } else if (actionFlag === EnigmailConstants.DOWNLOAD_KEY) {
       if (searchTerm.indexOf("0x") !== 0) {
         searchTerm = "0x" + searchTerm;
       }
       url += "/pks/lookup?search=" + searchTerm + "&op=get&options=mr";
-    }
-    else if (actionFlag === EnigmailConstants.SEARCH_KEY) {
-      url += "/pks/lookup?search=" + escape(searchTerm) + "&fingerprint=on&op=index&options=mr";
-    }
-    else if (actionFlag === EnigmailConstants.GET_SKS_CACERT) {
+    } else if (actionFlag === EnigmailConstants.SEARCH_KEY) {
+      url +=
+        "/pks/lookup?search=" +
+        escape(searchTerm) +
+        "&fingerprint=on&op=index&options=mr";
+    } else if (actionFlag === EnigmailConstants.GET_SKS_CACERT) {
       url = SKS_CACERT_URL;
     }
 
     return {
-      url: url,
+      url,
       host: keySrv.host,
-      method: method
+      method,
     };
   },
 
   /**
    * Upload, search or download keys from a keyserver
    * @param actionFlag:  Number  - Keyserver Action Flags: from EnigmailConstants
    * @param keyId:      String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<Number (Status-ID)>
    */
-  accessKeyServer: function(actionFlag, keyserver, keyId, listener) {
-    EnigmailLog.DEBUG(`keyserver.jsm: accessHkpInternal.accessKeyServer(${keyserver})\n`);
+  accessKeyServer(actionFlag, keyserver, keyId, listener) {
+    EnigmailLog.DEBUG(
+      `keyserver.jsm: accessHkpInternal.accessKeyServer(${keyserver})\n`
+    );
     if (keyserver === null) {
       keyserver = EnigmailKeyserverURIs.getDefaultKeyServer();
     }
 
     return new Promise((resolve, reject) => {
       let xmlReq = null;
-      if (listener && typeof(listener) === "object") {
+      if (listener && typeof listener === "object") {
         listener.onCancel = function() {
-          EnigmailLog.DEBUG(`keyserver.jsm: accessHkpInternal.accessKeyServer - onCancel() called\n`);
+          EnigmailLog.DEBUG(
+            `keyserver.jsm: accessHkpInternal.accessKeyServer - onCancel() called\n`
+          );
           if (xmlReq) {
             xmlReq.abort();
           }
           reject(createError(EnigmailConstants.KEYSERVER_ERR_ABORTED));
         };
       }
       if (actionFlag === EnigmailConstants.REFRESH_KEY) {
         // we don't (need to) distinguish between refresh and download for our internal protocol
@@ -241,234 +263,286 @@ const accessHkpInternal = {
       }
 
       let payLoad = this.buildHkpPayload(actionFlag, keyId);
       if (payLoad === null) {
         reject(createError(EnigmailConstants.KEYSERVER_ERR_UNKNOWN));
         return;
       }
 
-      let errorCode = 0;
-
       xmlReq = new XMLHttpRequest();
 
-      xmlReq.onload = function _onLoad() {
-        EnigmailLog.DEBUG("keyserver.jsm: accessHkpInternal: onload(): status=" + xmlReq.status + "\n");
+      xmlReq.onload = function() {
+        EnigmailLog.DEBUG(
+          "keyserver.jsm: accessHkpInternal: onload(): status=" +
+            xmlReq.status +
+            "\n"
+        );
         switch (actionFlag) {
           case EnigmailConstants.UPLOAD_KEY:
-            EnigmailLog.DEBUG("keyserver.jsm: accessHkpInternal: onload: " + xmlReq.responseText + "\n");
+            EnigmailLog.DEBUG(
+              "keyserver.jsm: accessHkpInternal: onload: " +
+                xmlReq.responseText +
+                "\n"
+            );
             if (xmlReq.status >= 400) {
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               resolve(0);
             }
             return;
 
           case EnigmailConstants.SEARCH_KEY:
           case EnigmailConstants.GET_SKS_CACERT:
             if (xmlReq.status === 404) {
               // key not found
               resolve("");
-            }
-            else if (xmlReq.status >= 400) {
+            } else if (xmlReq.status >= 400) {
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               resolve(xmlReq.responseText);
             }
             return;
 
           case EnigmailConstants.DOWNLOAD_KEY:
             if (xmlReq.status >= 400 && xmlReq.status < 500) {
               // key not found
               resolve(1);
-            }
-            else if (xmlReq.status >= 500) {
-              EnigmailLog.DEBUG("keyserver.jsm: accessHkpInternal: onload: " + xmlReq.responseText + "\n");
+            } else if (xmlReq.status >= 500) {
+              EnigmailLog.DEBUG(
+                "keyserver.jsm: accessHkpInternal: onload: " +
+                  xmlReq.responseText +
+                  "\n"
+              );
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               let errorMsgObj = {},
                 importedKeysObj = {};
-              let importMinimal = (xmlReq.responseText.length > 1024000 && (!EnigmailGpg.getGpgFeature("handles-huge-keys")));
-              let r = EnigmailKeyRing.importKey(null, false, xmlReq.responseText, "", errorMsgObj, importedKeysObj, importMinimal);
+              let importMinimal =
+                xmlReq.responseText.length > 1024000 &&
+                !EnigmailGpg.getGpgFeature("handles-huge-keys");
+              let r = EnigmailKeyRing.importKey(
+                null,
+                false,
+                xmlReq.responseText,
+                "",
+                errorMsgObj,
+                importedKeysObj,
+                importMinimal
+              );
               if (r === 0) {
                 resolve(importedKeysObj.value);
-              }
-              else {
-                reject(createError(EnigmailConstants.KEYSERVER_ERR_IMPORT_ERROR));
+              } else {
+                reject(
+                  createError(EnigmailConstants.KEYSERVER_ERR_IMPORT_ERROR)
+                );
               }
             }
             return;
         }
         resolve(-1);
       };
 
       xmlReq.onerror = function(e) {
-        EnigmailLog.DEBUG("keyserver.jsm: accessHkpInternal.accessKeyServer: onerror: " + e + "\n");
+        EnigmailLog.DEBUG(
+          "keyserver.jsm: accessHkpInternal.accessKeyServer: onerror: " +
+            e +
+            "\n"
+        );
         let err = EnigmailXhrUtils.createTCPErrorFromFailedXHR(e.target);
         switch (err.type) {
-          case 'SecurityCertificate':
-            reject(createError(EnigmailConstants.KEYSERVER_ERR_CERTIFICATE_ERROR));
+          case "SecurityCertificate":
+            reject(
+              createError(EnigmailConstants.KEYSERVER_ERR_CERTIFICATE_ERROR)
+            );
             break;
-          case 'SecurityProtocol':
+          case "SecurityProtocol":
             reject(createError(EnigmailConstants.KEYSERVER_ERR_SECURITY_ERROR));
             break;
-          case 'Network':
-            reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE));
+          case "Network":
+            reject(
+              createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE)
+            );
             break;
         }
         reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE));
       };
 
       xmlReq.onloadend = function() {
-        EnigmailLog.DEBUG("keyserver.jsm: accessHkpInternal.accessKeyServer: loadEnd\n");
+        EnigmailLog.DEBUG(
+          "keyserver.jsm: accessHkpInternal.accessKeyServer: loadEnd\n"
+        );
       };
 
-      let {
-        url,
-        host,
-        method
-      } = this.createRequestUrl(keyserver, actionFlag, keyId);
+      let { url, host, method } = this.createRequestUrl(
+        keyserver,
+        actionFlag,
+        keyId
+      );
 
-      if (host === HKPS_POOL_HOST && actionFlag !== EnigmailConstants.GET_SKS_CACERT) {
+      if (
+        host === HKPS_POOL_HOST &&
+        actionFlag !== EnigmailConstants.GET_SKS_CACERT
+      ) {
         this.getSksCACert().then(r => {
-          EnigmailLog.DEBUG(`keyserver.jsm: accessHkpInternal.accessKeyServer: getting ${url}\n`);
+          EnigmailLog.DEBUG(
+            `keyserver.jsm: accessHkpInternal.accessKeyServer: getting ${url}\n`
+          );
           xmlReq.open(method, url);
           xmlReq.send(payLoad);
         });
-      }
-      else {
-        EnigmailLog.DEBUG(`keyserver.jsm: accessHkpInternal.accessKeyServer: requesting ${url}\n`);
+      } else {
+        EnigmailLog.DEBUG(
+          `keyserver.jsm: accessHkpInternal.accessKeyServer: requesting ${url}\n`
+        );
         xmlReq.open(method, url);
         xmlReq.send(payLoad);
       }
     });
   },
 
-  installSksCACert: async function() {
+  async installSksCACert() {
     EnigmailLog.DEBUG(`keyserver.jsm: installSksCACert()\n`);
-    let certDb = Cc["@mozilla.org/security/x509certdb;1"].getService(Ci.nsIX509CertDB);
+    let certDb = Cc["@mozilla.org/security/x509certdb;1"].getService(
+      Ci.nsIX509CertDB
+    );
     try {
-      let certTxt = await this.accessKeyServer(EnigmailConstants.GET_SKS_CACERT, "", "", null);
+      let certTxt = await this.accessKeyServer(
+        EnigmailConstants.GET_SKS_CACERT,
+        "",
+        "",
+        null
+      );
       const BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
       const END_CERT = "-----END CERTIFICATE-----";
 
       certTxt = certTxt.replace(/[\r\n]/g, "");
       let begin = certTxt.indexOf(BEGIN_CERT);
       let end = certTxt.indexOf(END_CERT);
       let certData = certTxt.substring(begin + BEGIN_CERT.length, end);
       let x509cert = certDb.addCertFromBase64(certData, "C,C,C", "");
       return x509cert;
-    }
-    catch (x) {
+    } catch (x) {
       return null;
     }
   },
 
   /**
    * Get the CA certificate for the HKPS sks-keyserver pool
    */
-  getSksCACert: async function() {
+  async getSksCACert() {
     EnigmailLog.DEBUG(`keyserver.jsm: getSksCACert()\n`);
-    let certDb = Cc["@mozilla.org/security/x509certdb;1"].getService(Ci.nsIX509CertDB);
+    let certDb = Cc["@mozilla.org/security/x509certdb;1"].getService(
+      Ci.nsIX509CertDB
+    );
     let cert = null;
 
     for (cert of certDb.getCerts().getEnumerator()) {
-      if (cert.subjectName === SKS_CACERT_SUBJECTNAME && cert.certType === Ci.nsIX509Cert.CA_CERT) {
+      if (
+        cert.subjectName === SKS_CACERT_SUBJECTNAME &&
+        cert.certType === Ci.nsIX509Cert.CA_CERT
+      ) {
         return cert;
       }
     }
 
     cert = await this.installSksCACert();
     return cert;
   },
 
   /**
    * Download keys from a keyserver
    * @param keyIDs:      String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<...>
    */
-  download: async function(keyIDs, keyserver, listener = null) {
+  async download(keyIDs, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessHkpInternal.download(${keyIDs})\n`);
     let keyIdArr = keyIDs.split(/ +/);
     let retObj = {
       result: 0,
       errorDetails: "",
-      keyList: []
+      keyList: [],
     };
 
     for (let i = 0; i < keyIdArr.length; i++) {
       try {
-        let r = await this.accessKeyServer(EnigmailConstants.DOWNLOAD_KEY, keyserver, keyIdArr[i], listener);
+        let r = await this.accessKeyServer(
+          EnigmailConstants.DOWNLOAD_KEY,
+          keyserver,
+          keyIdArr[i],
+          listener
+        );
         if (Array.isArray(r)) {
           retObj.keyList = retObj.keyList.concat(r);
         }
-      }
-      catch (ex) {
+      } catch (ex) {
         retObj.result = ex.result;
         retObj.errorDetails = ex.errorDetails;
         throw retObj;
       }
 
       if (listener && "onProgress" in listener) {
-        listener.onProgress((i + 1) / keyIdArr.length * 100);
+        listener.onProgress(((i + 1) / keyIdArr.length) * 100);
       }
     }
 
     return retObj;
   },
 
-  refresh: function(keyServer, listener = null) {
-    let keyList = EnigmailKeyRing.getAllKeys().keyList.map(keyObj => {
-      return "0x" + keyObj.fpr;
-    }).join(" ");
+  refresh(keyServer, listener = null) {
+    let keyList = EnigmailKeyRing.getAllKeys()
+      .keyList.map(keyObj => {
+        return "0x" + keyObj.fpr;
+      })
+      .join(" ");
 
     return this.download(keyList, keyServer, listener);
   },
 
   /**
    * Upload keys to a keyserver
    * @param keyIDs: String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<...>
    */
-  upload: async function(keyIDs, keyserver, listener = null) {
+  async upload(keyIDs, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessHkpInternal.upload(${keyIDs})\n`);
     let keyIdArr = keyIDs.split(/ +/);
     let retObj = {
       result: 0,
       errorDetails: "",
-      keyList: []
+      keyList: [],
     };
 
     for (let i = 0; i < keyIdArr.length; i++) {
       try {
-        let r = await this.accessKeyServer(EnigmailConstants.UPLOAD_KEY, keyserver, keyIdArr[i], listener);
+        let r = await this.accessKeyServer(
+          EnigmailConstants.UPLOAD_KEY,
+          keyserver,
+          keyIdArr[i],
+          listener
+        );
         if (r === 0) {
           retObj.keyList.push(keyIdArr[i]);
-        }
-        else {
+        } else {
           retObj.result = r;
         }
-      }
-      catch (ex) {
+      } catch (ex) {
         retObj.result = ex.result;
         retObj.errorDetails = ex.errorDetails;
         throw retObj;
       }
 
       if (listener && "onProgress" in listener) {
-        listener.onProgress((i + 1) / keyIdArr.length * 100);
+        listener.onProgress(((i + 1) / keyIdArr.length) * 100);
       }
     }
 
     return retObj;
   },
 
   /**
    * Search for keys on a keyserver
@@ -482,259 +556,275 @@ const accessHkpInternal = {
    *         PubKeys: Object with:
    *           - keyId: String
    *           - keyLen: String
    *           - keyType: String
    *           - created: String (YYYY-MM-DD)
    *           - status: String: one of ''=valid, r=revoked, e=expired
    *           - uid: Array of Strings with UIDs
    */
-  search: async function(searchTerm, keyserver, listener = null) {
-    EnigmailLog.DEBUG(`keyserver.jsm: accessHkpInternal.search(${searchTerm})\n`);
+  async search(searchTerm, keyserver, listener = null) {
+    EnigmailLog.DEBUG(
+      `keyserver.jsm: accessHkpInternal.search(${searchTerm})\n`
+    );
     let retObj = {
       result: 0,
       errorDetails: "",
-      pubKeys: []
+      pubKeys: [],
     };
     let key = null;
 
     let searchArr = searchTerm.split(/ +/);
 
-    try {
-      for (let k in searchArr) {
-        let r = await this.accessKeyServer(EnigmailConstants.SEARCH_KEY, keyserver, searchArr[k], listener);
-
-        let lines = r.split(/\r?\n/);
-
-        for (var i = 0; i < lines.length; i++) {
-          let line = lines[i].split(/:/).map(unescape);
-          if (line.length <= 1) continue;
+    for (let k in searchArr) {
+      let r = await this.accessKeyServer(
+        EnigmailConstants.SEARCH_KEY,
+        keyserver,
+        searchArr[k],
+        listener
+      );
 
-          switch (line[0]) {
-            case "info":
-              if (line[1] !== "1") {
-                // protocol version not supported
-                throw {
-                  result: 7,
-                  errorDetails: EnigmailLocale.getString("keyserver.error.unsupported"),
-                  pubKeys: []
-                };
-              }
-              break;
-            case "pub":
-              if (line.length >= 6) {
-                if (key) {
-                  retObj.pubKeys.push(key);
-                  key = null;
-                }
-                let dat = new Date(line[4] * 1000);
-                let month = String(dat.getMonth() + 101).substr(1);
-                let day = String(dat.getDate() + 100).substr(1);
-                key = {
-                  keyId: line[1],
-                  keyLen: line[3],
-                  keyType: line[2],
-                  created: dat.getFullYear() + "-" + month + "-" + day,
-                  uid: [],
-                  status: line[6]
-                };
-              }
-              break;
-            case "uid":
-              key.uid.push(EnigmailData.convertToUnicode(line[1].trim(), "utf-8"));
-          }
+      let lines = r.split(/\r?\n/);
+
+      for (var i = 0; i < lines.length; i++) {
+        let line = lines[i].split(/:/).map(unescape);
+        if (line.length <= 1) {
+          continue;
         }
 
-        if (key) {
-          retObj.pubKeys.push(key);
+        switch (line[0]) {
+          case "info":
+            if (line[1] !== "1") {
+              // protocol version not supported
+              retObj.result = 7;
+              retObj.errorDetails = EnigmailLocale.getString(
+                "keyserver.error.unsupported"
+              );
+              retObj.pubKeys = [];
+              return retObj;
+            }
+            break;
+          case "pub":
+            if (line.length >= 6) {
+              if (key) {
+                retObj.pubKeys.push(key);
+                key = null;
+              }
+              let dat = new Date(line[4] * 1000);
+              let month = String(dat.getMonth() + 101).substr(1);
+              let day = String(dat.getDate() + 100).substr(1);
+              key = {
+                keyId: line[1],
+                keyLen: line[3],
+                keyType: line[2],
+                created: dat.getFullYear() + "-" + month + "-" + day,
+                uid: [],
+                status: line[6],
+              };
+            }
+            break;
+          case "uid":
+            key.uid.push(
+              EnigmailData.convertToUnicode(line[1].trim(), "utf-8")
+            );
         }
       }
-    }
-    catch (ex) {
-      retObj.result = ex.result;
-      retObj.errorDetails = ex.errorDetails;
-      throw retObj;
+
+      if (key) {
+        retObj.pubKeys.push(key);
+      }
     }
 
     return retObj;
-  }
+  },
 };
 
 /**
  Object to handle KeyBase requests (search & download only)
  */
 const accessKeyBase = {
   /**
    * return the URL and the HTTP access method for a given action
    */
-  createRequestUrl: function(actionFlag, searchTerm) {
-    const method = "GET";
-
+  createRequestUrl(actionFlag, searchTerm) {
     let url = "https://keybase.io/_/api/1.0/user/";
 
     if (actionFlag === EnigmailConstants.UPLOAD_KEY) {
       // not supported
-      throw Components.results.NS_ERROR_FAILURE;
-    }
-    else if (actionFlag === EnigmailConstants.DOWNLOAD_KEY) {
+      throw Cr.NS_ERROR_FAILURE;
+    } else if (actionFlag === EnigmailConstants.DOWNLOAD_KEY) {
       if (searchTerm.indexOf("0x") === 0) {
         searchTerm = searchTerm.substr(0, 40);
       }
-      url += "lookup.json?key_fingerprint=" + escape(searchTerm) + "&fields=public_keys";
-    }
-    else if (actionFlag === EnigmailConstants.SEARCH_KEY) {
+      url +=
+        "lookup.json?key_fingerprint=" +
+        escape(searchTerm) +
+        "&fields=public_keys";
+    } else if (actionFlag === EnigmailConstants.SEARCH_KEY) {
       url += "autocomplete.json?q=" + escape(searchTerm);
     }
 
     return {
-      url: url,
-      method: "GET"
+      url,
+      method: "GET",
     };
   },
 
   /**
    * Upload, search or download keys from a keyserver
    * @param actionFlag:  Number  - Keyserver Action Flags: from EnigmailConstants
    * @param keyId:      String  - space-separated list of search terms or key IDs
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<Number (Status-ID)>
    */
-  accessKeyServer: function(actionFlag, keyId, listener) {
+  accessKeyServer(actionFlag, keyId, listener) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessKeyBase: accessKeyServer()\n`);
 
     return new Promise((resolve, reject) => {
       let xmlReq = null;
-      if (listener && typeof(listener) === "object") {
+      if (listener && typeof listener === "object") {
         listener.onCancel = function() {
-          EnigmailLog.DEBUG(`keyserver.jsm: accessKeyBase: accessKeyServer - onCancel() called\n`);
+          EnigmailLog.DEBUG(
+            `keyserver.jsm: accessKeyBase: accessKeyServer - onCancel() called\n`
+          );
           if (xmlReq) {
             xmlReq.abort();
           }
           reject(createError(EnigmailConstants.KEYSERVER_ERR_ABORTED));
         };
       }
       if (actionFlag === EnigmailConstants.REFRESH_KEY) {
         // we don't (need to) distinguish between refresh and download for our internal protocol
         actionFlag = EnigmailConstants.DOWNLOAD_KEY;
       }
 
-      let errorCode = 0;
-
       xmlReq = new XMLHttpRequest();
 
-      xmlReq.onload = function _onLoad() {
-        EnigmailLog.DEBUG("keyserver.jsm: onload(): status=" + xmlReq.status + "\n");
+      xmlReq.onload = function() {
+        EnigmailLog.DEBUG(
+          "keyserver.jsm: onload(): status=" + xmlReq.status + "\n"
+        );
         switch (actionFlag) {
           case EnigmailConstants.SEARCH_KEY:
             if (xmlReq.status >= 400) {
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               resolve(xmlReq.responseText);
             }
             return;
 
           case EnigmailConstants.DOWNLOAD_KEY:
             if (xmlReq.status >= 400 && xmlReq.status < 500) {
               // key not found
               resolve([]);
-            }
-            else if (xmlReq.status >= 500) {
-              EnigmailLog.DEBUG("keyserver.jsm: onload: " + xmlReq.responseText + "\n");
+            } else if (xmlReq.status >= 500) {
+              EnigmailLog.DEBUG(
+                "keyserver.jsm: onload: " + xmlReq.responseText + "\n"
+              );
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               try {
                 let resp = JSON.parse(xmlReq.responseText);
                 let imported = [];
 
                 if (resp.status.code === 0) {
                   for (let hit in resp.them) {
-                    EnigmailLog.DEBUG(JSON.stringify(resp.them[hit].public_keys.primary) + "\n");
+                    EnigmailLog.DEBUG(
+                      JSON.stringify(resp.them[hit].public_keys.primary) + "\n"
+                    );
 
                     if (resp.them[hit] !== null) {
                       let errorMsgObj = {},
                         importedKeysObj = {};
-                      let r = EnigmailKeyRing.importKey(null, false, resp.them[hit].public_keys.primary.bundle, "", errorMsgObj, importedKeysObj);
+                      let r = EnigmailKeyRing.importKey(
+                        null,
+                        false,
+                        resp.them[hit].public_keys.primary.bundle,
+                        "",
+                        errorMsgObj,
+                        importedKeysObj
+                      );
                       if (r === 0) {
                         imported.push(importedKeysObj.value);
                       }
                     }
                   }
                 }
                 resolve(imported);
-              }
-              catch (ex) {
+              } catch (ex) {
                 reject(createError(EnigmailConstants.KEYSERVER_ERR_UNKNOWN));
               }
             }
             return;
         }
         resolve(-1);
       };
 
       xmlReq.onerror = function(e) {
         EnigmailLog.DEBUG("keyserver.jsm: accessKeyBase: onerror: " + e + "\n");
         let err = EnigmailXhrUtils.createTCPErrorFromFailedXHR(e.target);
         switch (err.type) {
-          case 'SecurityCertificate':
-            reject(createError(EnigmailConstants.KEYSERVER_ERR_CERTIFICATE_ERROR));
+          case "SecurityCertificate":
+            reject(
+              createError(EnigmailConstants.KEYSERVER_ERR_CERTIFICATE_ERROR)
+            );
             break;
-          case 'SecurityProtocol':
+          case "SecurityProtocol":
             reject(createError(EnigmailConstants.KEYSERVER_ERR_SECURITY_ERROR));
             break;
-          case 'Network':
-            reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE));
+          case "Network":
+            reject(
+              createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE)
+            );
             break;
         }
         reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE));
       };
 
       xmlReq.onloadend = function() {
         EnigmailLog.DEBUG("keyserver.jsm: accessKeyBase: loadEnd\n");
       };
 
-      let {
-        url,
-        method
-      } = this.createRequestUrl(actionFlag, keyId);
+      let { url, method } = this.createRequestUrl(actionFlag, keyId);
 
       EnigmailLog.DEBUG(`keyserver.jsm: accessKeyBase: requesting ${url}\n`);
       xmlReq.open(method, url);
       xmlReq.send("");
     });
   },
 
   /**
    * Download keys from a KeyBase
    * @param keyIDs:      String  - space-separated list of search terms or key IDs
    * @param keyserver:   (not used for keybase)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<...>
    */
-  download: async function(keyIDs, keyserver, listener = null) {
+  async download(keyIDs, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessKeyBase: download()\n`);
     let keyIdArr = keyIDs.split(/ +/);
     let retObj = {
       result: 0,
       errorDetails: "",
-      keyList: []
+      keyList: [],
     };
 
-
     for (let i = 0; i < keyIdArr.length; i++) {
       try {
-        let r = await this.accessKeyServer(EnigmailConstants.DOWNLOAD_KEY, keyIdArr[i], listener);
+        let r = await this.accessKeyServer(
+          EnigmailConstants.DOWNLOAD_KEY,
+          keyIdArr[i],
+          listener
+        );
         if (r.length > 0) {
           retObj.keyList = retObj.keyList.concat(r);
         }
-      }
-      catch (ex) {
+      } catch (ex) {
         retObj.result = ex.result;
         retObj.errorDetails = ex.result;
         throw retObj;
       }
 
       if (listener && "onProgress" in listener) {
         listener.onProgress(i / keyIdArr.length);
       }
@@ -756,90 +846,102 @@ const accessKeyBase = {
    *           - keyId: String
    *           - keyLen: String
    *           - keyType: String
    *           - created: String (YYYY-MM-DD)
    *           - status: String: one of ''=valid, r=revoked, e=expired
    *           - uid: Array of Strings with UIDs
 
    */
-  search: async function(searchTerm, keyserver, listener = null) {
+  async search(searchTerm, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessKeyBase: search()\n`);
     let retObj = {
       result: 0,
       errorDetails: "",
-      pubKeys: []
+      pubKeys: [],
     };
 
-    let key = {};
-
     try {
-      let r = await this.accessKeyServer(EnigmailConstants.SEARCH_KEY, searchTerm, listener);
+      let r = await this.accessKeyServer(
+        EnigmailConstants.SEARCH_KEY,
+        searchTerm,
+        listener
+      );
 
       let res = JSON.parse(r);
       let completions = res.completions;
 
       for (let hit in completions) {
-        if (completions[hit] && completions[hit].components.key_fingerprint !== undefined) {
+        if (
+          completions[hit] &&
+          completions[hit].components.key_fingerprint !== undefined
+        ) {
           let uid = completions[hit].components.username.val;
           if ("full_name" in completions[hit].components) {
             uid += " (" + completions[hit].components.full_name.val + ")";
           }
           let key = {
-            keyId: completions[hit].components.key_fingerprint.val.toUpperCase(),
-            keyLen: completions[hit].components.key_fingerprint.nbits.toString(),
-            keyType: completions[hit].components.key_fingerprint.algo.toString(),
+            keyId: completions[
+              hit
+            ].components.key_fingerprint.val.toUpperCase(),
+            keyLen: completions[
+              hit
+            ].components.key_fingerprint.nbits.toString(),
+            keyType: completions[
+              hit
+            ].components.key_fingerprint.algo.toString(),
             created: 0, //date.toDateString(),
             uid: [uid],
-            status: ""
+            status: "",
           };
           retObj.pubKeys.push(key);
         }
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       retObj.result = ex.result;
       retObj.errorDetails = ex.errorDetails;
       throw retObj;
     }
 
     return retObj;
   },
 
-  upload: function() {
-    throw Components.results.NS_ERROR_FAILURE;
+  upload() {
+    throw Cr.NS_ERROR_FAILURE;
   },
 
-  refresh: function(keyServer, listener = null) {
+  refresh(keyServer, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessKeyBase: refresh()\n`);
-    let keyList = EnigmailKeyRing.getAllKeys().keyList.map(keyObj => {
-      return "0x" + keyObj.fpr;
-    }).join(" ");
+    let keyList = EnigmailKeyRing.getAllKeys()
+      .keyList.map(keyObj => {
+        return "0x" + keyObj.fpr;
+      })
+      .join(" ");
 
     return this.download(keyList, keyServer, listener);
-  }
+  },
 };
 
-
 /**
  Object to handle HKP/HKPS and LDAP/LDAPS requests via GnuPG
  */
 const accessGnuPG = {
-
   /**
    * Upload, search or download keys from a keyserver
    * @param actionFlag:  Number  - Keyserver Action Flags: from EnigmailConstants
    * @param keyId:       String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return Promise<Object> Object from execAsync
    */
-  accessKeyServer: function(actionFlag, keyserver, keyId, listener) {
-    EnigmailLog.DEBUG(`keyserver.jsm: accessGnuPG: accessKeyServer(${keyserver})\n`);
+  accessKeyServer(actionFlag, keyserver, keyId, listener) {
+    EnigmailLog.DEBUG(
+      `keyserver.jsm: accessGnuPG: accessKeyServer(${keyserver})\n`
+    );
     throw new Error("Not implemented");
 
     /*
     if (keyserver === null) {
       keyserver = EnigmailKeyserverURIs.getDefaultKeyServer();
     }
 
     let proxyHost = EnigmailHttpProxy.getHttpProxy();
@@ -850,27 +952,29 @@ const accessGnuPG = {
       case EnigmailConstants.DOWNLOAD_KEY:
         break;
       case EnigmailConstants.UPLOAD_KEY:
         break;
     }
     */
   },
 
-  parseStatusMsg: function(execResult) {
+  parseStatusMsg(execResult) {
     let errorCode = 0,
       errorType = null;
 
     // Find the 1st FAILURE message in the gpg status output
-    let m = execResult.stderrData.match(/^\[GNUPG:\] (FAILURE|ERROR) ([^ ]+ )(\d+)/m);
+    let m = execResult.stderrData.match(
+      /^\[GNUPG:\] (FAILURE|ERROR) ([^ ]+ )(\d+)/m
+    );
 
     if (m && m.length >= 4 && m[3].search(/^[0-9]+$/) === 0) {
       let errorNumber = Number(m[3]);
       //let sourceSystem = errorNumber >> 24;
-      errorCode = errorNumber & 0xFFFFFF;
+      errorCode = errorNumber & 0xffffff;
 
       switch (errorCode) {
         case 58: // no data
           break;
         case 32793: // connection refused
         case 32810: // host unreachable
         case 220: // Server not found (no name)
           errorType = EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE;
@@ -890,106 +994,120 @@ const accessGnuPG = {
       }
     }
 
     if (execResult.isKilled !== 0) {
       errorType = EnigmailConstants.KEYSERVER_ERR_ABORTED;
     }
 
     if (errorType !== null) {
-      EnigmailLog.DEBUG(`keyserver.jsm: accessGnuPG.parseStatusMsg: got errorCode=${errorCode}\n`);
+      EnigmailLog.DEBUG(
+        `keyserver.jsm: accessGnuPG.parseStatusMsg: got errorCode=${errorCode}\n`
+      );
       return createError(errorType);
     }
 
     return null;
   },
   /**
    * Download keys from a keyserver
    * @param keyIDs:      String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<...>
    */
-  download: async function(keyIDs, keyserver, listener = null) {
+  async download(keyIDs, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessGnuPG.download(${keyIDs})\n`);
     let retObj = {
       result: 0,
       errorDetails: "",
-      keyList: []
+      keyList: [],
     };
     let keyIdArr = keyIDs.split(/ +/);
 
     for (let i = 0; i < keyIdArr.length; i++) {
-      let r = await this.accessKeyServer(EnigmailConstants.DOWNLOAD_KEY, keyserver, keyIdArr[i], listener);
+      let r = await this.accessKeyServer(
+        EnigmailConstants.DOWNLOAD_KEY,
+        keyserver,
+        keyIdArr[i],
+        listener
+      );
 
       let exitValue = this.parseStatusMsg(r);
       if (exitValue) {
         exitValue.keyList = [];
         throw exitValue;
       }
 
       var statusLines = r.statusMsg.split(/\r?\n/);
 
       for (let j = 0; j < statusLines.length; j++) {
         let matches = statusLines[j].match(/IMPORT_OK ([0-9]+) (\w+)/);
-        if (matches && (matches.length > 2)) {
+        if (matches && matches.length > 2) {
           retObj.keyList.push(matches[2]);
           EnigmailKeyRing.updateKeys([matches[2]]);
         }
       }
 
       if (listener && "onProgress" in listener) {
-        listener.onProgress((i + 1) / keyIdArr.length * 100);
+        listener.onProgress(((i + 1) / keyIdArr.length) * 100);
       }
     }
 
     return retObj;
   },
 
-  refresh: function(keyServer, listener = null) {
-    let keyList = EnigmailKeyRing.getAllKeys().keyList.map(keyObj => {
-      return "0x" + keyObj.fpr;
-    }).join(" ");
+  refresh(keyServer, listener = null) {
+    let keyList = EnigmailKeyRing.getAllKeys()
+      .keyList.map(keyObj => {
+        return "0x" + keyObj.fpr;
+      })
+      .join(" ");
 
     return this.download(keyList, keyServer, listener);
   },
 
   /**
    * Upload keys to a keyserver
    * @param keyIDs: String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<...>
    */
-  upload: async function(keyIDs, keyserver, listener = null) {
+  async upload(keyIDs, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessGnuPG.upload(${keyIDs})\n`);
     let keyIdArr = keyIDs.split(/ +/);
     let retObj = {
       result: 0,
       errorDetails: "",
-      keyList: []
+      keyList: [],
     };
 
     for (let i = 0; i < keyIdArr.length; i++) {
-      let r = await this.accessKeyServer(EnigmailConstants.UPLOAD_KEY, keyserver, keyIdArr[i], listener);
+      let r = await this.accessKeyServer(
+        EnigmailConstants.UPLOAD_KEY,
+        keyserver,
+        keyIdArr[i],
+        listener
+      );
 
       let exitValue = this.parseStatusMsg(r);
       if (exitValue) {
         exitValue.keyList = [];
         throw exitValue;
       }
 
       if (r.exitCode === 0) {
         retObj.keyList.push(keyIdArr[i]);
       }
 
       if (listener && "onProgress" in listener) {
-        listener.onProgress((i + 1) / keyIdArr.length * 100);
+        listener.onProgress(((i + 1) / keyIdArr.length) * 100);
       }
     }
 
     return retObj;
   },
 
   /**
    * Search for keys on a keyserver
@@ -1003,96 +1121,97 @@ const accessGnuPG = {
    *         PubKeys: Object with:
    *           - keyId: String
    *           - keyLen: String
    *           - keyType: String
    *           - created: String (YYYY-MM-DD)
    *           - status: String: one of ''=valid, r=revoked, e=expired
    *           - uid: Array of Strings with UIDs
    */
-  search: async function(searchTerm, keyserver, listener = null) {
+  async search(searchTerm, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessGnuPG.search(${searchTerm})\n`);
     let retObj = {
       result: 0,
       errorDetails: "",
-      pubKeys: []
+      pubKeys: [],
     };
     let key = null;
 
-    try {
-      let r = await this.accessKeyServer(EnigmailConstants.SEARCH_KEY, keyserver, searchTerm, listener);
+    let r = await this.accessKeyServer(
+      EnigmailConstants.SEARCH_KEY,
+      keyserver,
+      searchTerm,
+      listener
+    );
 
-      let exitValue = this.parseStatusMsg(r);
-      if (exitValue) {
-        exitValue.pubKeys = [];
-        throw exitValue;
+    let exitValue = this.parseStatusMsg(r);
+    if (exitValue) {
+      retObj.result = exitValue.result;
+      retObj.errorDetails = exitValue.errorDetails;
+      retObj.pubKeys = [];
+      return retObj;
+    }
+
+    let lines = r.stdoutData.split(/\r?\n/);
+
+    for (var i = 0; i < lines.length; i++) {
+      let line = lines[i].split(/:/).map(unescape);
+      if (line.length <= 1) {
+        continue;
       }
 
-      let lines = r.stdoutData.split(/\r?\n/);
-
-      for (var i = 0; i < lines.length; i++) {
-        let line = lines[i].split(/:/).map(unescape);
-        if (line.length <= 1) continue;
-
-        switch (line[0]) {
-          case "info":
-            if (line[1] !== "1") {
-              // protocol version not supported
-              throw {
-                result: 7,
-                errorDetails: EnigmailLocale.getString("keyserver.error.unsupported"),
-                pubKeys: []
-              };
+      switch (line[0]) {
+        case "info":
+          if (line[1] !== "1") {
+            // protocol version not supported
+            retObj.result = 7;
+            retObj.errorDetails = EnigmailLocale.getString(
+              "keyserver.error.unsupported"
+            );
+            retObj.pubKeys = [];
+            return retObj;
+          }
+          break;
+        case "pub":
+          if (line.length >= 6) {
+            if (key) {
+              retObj.pubKeys.push(key);
+              key = null;
             }
-            break;
-          case "pub":
-            if (line.length >= 6) {
-              if (key) {
-                retObj.pubKeys.push(key);
-                key = null;
-              }
-              let dat = new Date(line[4] * 1000);
-              let month = String(dat.getMonth() + 101).substr(1);
-              let day = String(dat.getDate() + 100).substr(1);
-              key = {
-                keyId: line[1],
-                keyLen: line[3],
-                keyType: line[2],
-                created: dat.getFullYear() + "-" + month + "-" + day,
-                uid: [],
-                status: line[6]
-              };
-            }
-            break;
-          case "uid":
-            key.uid.push(EnigmailData.convertToUnicode(line[1].trim(), "utf-8"));
-        }
-      }
-
-      if (key) {
-        retObj.pubKeys.push(key);
+            let dat = new Date(line[4] * 1000);
+            let month = String(dat.getMonth() + 101).substr(1);
+            let day = String(dat.getDate() + 100).substr(1);
+            key = {
+              keyId: line[1],
+              keyLen: line[3],
+              keyType: line[2],
+              created: dat.getFullYear() + "-" + month + "-" + day,
+              uid: [],
+              status: line[6],
+            };
+          }
+          break;
+        case "uid":
+          key.uid.push(EnigmailData.convertToUnicode(line[1].trim(), "utf-8"));
       }
     }
-    catch (ex) {
-      retObj.result = ex.result;
-      retObj.errorDetails = ex.errorDetails;
-      throw retObj;
+
+    if (key) {
+      retObj.pubKeys.push(key);
     }
 
     return retObj;
-  }
+  },
 };
 
-
 function getAccessType(keyserver) {
   if (keyserver === null) {
     keyserver = EnigmailKeyserverURIs.getDefaultKeyServer();
   }
 
-
   let srv = parseKeyserverUrl(keyserver);
   switch (srv.protocol) {
     case "keybase":
       return accessKeyBase;
     case "ldap":
     case "ldaps":
       return accessGnuPG;
     case "vks":
@@ -1105,129 +1224,137 @@ function getAccessType(keyserver) {
 
   if (EnigmailPrefs.getPref("useGpgKeysTool")) {
     return accessGnuPG;
   }
 
   return accessHkpInternal;
 }
 
-
 /**
  Object to handle VKS requests (for example keys.openpgp.org)
  */
 const accessVksServer = {
   /**
    * Create the payload of VKS requests (currently upload only)
    *
    */
-  buildJsonPayload: function(actionFlag, searchTerms, locale) {
+  buildJsonPayload(actionFlag, searchTerms, locale) {
     let payLoad = null,
       keyData = "";
 
     switch (actionFlag) {
       case EnigmailConstants.UPLOAD_KEY:
         keyData = EnigmailKeyRing.extractKey(false, searchTerms, null, {}, {});
-        if (keyData.length === 0) return null;
+        if (keyData.length === 0) {
+          return null;
+        }
 
         payLoad = JSON.stringify({
-          keytext: keyData
+          keytext: keyData,
         });
         return payLoad;
 
       case EnigmailConstants.GET_CONFIRMATION_LINK:
         payLoad = JSON.stringify({
           token: searchTerms.token,
           addresses: searchTerms.addresses,
-          locale: [locale]
+          locale: [locale],
         });
         return payLoad;
 
       case EnigmailConstants.DOWNLOAD_KEY:
       case EnigmailConstants.SEARCH_KEY:
       case EnigmailConstants.GET_SKS_CACERT:
         return "";
     }
 
     // other actions are not yet implemented
     return null;
   },
 
   /**
    * return the URL and the HTTP access method for a given action
    */
-  createRequestUrl: function(keyserver, actionFlag, searchTerm) {
+  createRequestUrl(keyserver, actionFlag, searchTerm) {
     let keySrv = parseKeyserverUrl(keyserver);
     let contentType = "text/plain;charset=UTF-8";
 
     let method = "GET";
 
     let url = "https://" + keySrv.host + ":443";
 
     if (actionFlag === EnigmailConstants.UPLOAD_KEY) {
       url += "/vks/v1/upload";
       method = "POST";
       contentType = "application/json";
-    }
-    else if (actionFlag === EnigmailConstants.GET_CONFIRMATION_LINK) {
+    } else if (actionFlag === EnigmailConstants.GET_CONFIRMATION_LINK) {
       url += "/vks/v1/request-verify";
       method = "POST";
       contentType = "application/json";
-    }
-    else if (actionFlag === EnigmailConstants.DOWNLOAD_KEY || actionFlag === EnigmailConstants.SEARCH_KEY) {
+    } else if (
+      actionFlag === EnigmailConstants.DOWNLOAD_KEY ||
+      actionFlag === EnigmailConstants.SEARCH_KEY
+    ) {
       if (searchTerm) {
         let lookup = "/vks/";
         if (searchTerm.indexOf("0x") === 0) {
           searchTerm = searchTerm.substr(2);
-          if (searchTerm.length == 16 && searchTerm.search(/^[A-F0-9]+$/) === 0) {
+          if (
+            searchTerm.length == 16 &&
+            searchTerm.search(/^[A-F0-9]+$/) === 0
+          ) {
             lookup = "/vks/v1/by-keyid/" + searchTerm;
-          }
-          else if (searchTerm.length == 40 && searchTerm.search(/^[A-F0-9]+$/) === 0) {
+          } else if (
+            searchTerm.length == 40 &&
+            searchTerm.search(/^[A-F0-9]+$/) === 0
+          ) {
             lookup = "/vks/v1/by-fingerprint/" + searchTerm;
           }
-        }
-        else {
+        } else {
           try {
             searchTerm = EnigmailFuncs.stripEmail(searchTerm);
-          }
-          catch (x) {}
+          } catch (x) {}
           lookup = "/vks/v1/by-email/" + searchTerm;
         }
         url += lookup;
       }
     }
 
     return {
-      url: url,
-      host: keySrv.host,
-      method: method,
-      contentType: contentType
+      url,
+      method,
+      contentType,
     };
   },
 
   /**
    * Upload, search or download keys from a keyserver
    * @param actionFlag:  Number  - Keyserver Action Flags: from EnigmailConstants
    * @param keyId:       String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<Number (Status-ID)>
    */
-  accessKeyServer: function(actionFlag, keyserver, keyId, listener) {
-    EnigmailLog.DEBUG(`keyserver.jsm: accessVksServer.accessKeyServer(${keyserver})\n`);
+  accessKeyServer(actionFlag, keyserver, keyId, listener) {
+    EnigmailLog.DEBUG(
+      `keyserver.jsm: accessVksServer.accessKeyServer(${keyserver})\n`
+    );
     if (keyserver === null) {
       keyserver = "keys.openpgp.org";
     }
 
     return new Promise((resolve, reject) => {
       let xmlReq = null;
-      if (listener && typeof(listener) === "object") {
+      if (listener && typeof listener === "object") {
         listener.onCancel = function() {
-          EnigmailLog.DEBUG(`keyserver.jsm: accessVksServer.accessKeyServer - onCancel() called\n`);
+          EnigmailLog.DEBUG(
+            `keyserver.jsm: accessVksServer.accessKeyServer - onCancel() called\n`
+          );
           if (xmlReq) {
             xmlReq.abort();
           }
           reject(createError(EnigmailConstants.KEYSERVER_ERR_ABORTED));
         };
       }
       if (actionFlag === EnigmailConstants.REFRESH_KEY) {
         // we don't (need to) distinguish between refresh and download for our internal protocol
@@ -1236,172 +1363,206 @@ const accessVksServer = {
 
       let uiLocale = EnigmailLocale.getUILocale();
       let payLoad = this.buildJsonPayload(actionFlag, keyId, uiLocale);
       if (payLoad === null) {
         reject(createError(EnigmailConstants.KEYSERVER_ERR_UNKNOWN));
         return;
       }
 
-      let errorCode = 0;
-
       xmlReq = new XMLHttpRequest();
 
-      xmlReq.onload = function _onLoad() {
-        EnigmailLog.DEBUG("keyserver.jsm: accessVksServer.onload(): status=" + xmlReq.status + "\n");
+      xmlReq.onload = function() {
+        EnigmailLog.DEBUG(
+          "keyserver.jsm: accessVksServer.onload(): status=" +
+            xmlReq.status +
+            "\n"
+        );
         switch (actionFlag) {
           case EnigmailConstants.UPLOAD_KEY:
           case EnigmailConstants.GET_CONFIRMATION_LINK:
-
-            EnigmailLog.DEBUG("keyserver.jsm: accessVksServer.onload: " + xmlReq.responseText + "\n");
+            EnigmailLog.DEBUG(
+              "keyserver.jsm: accessVksServer.onload: " +
+                xmlReq.responseText +
+                "\n"
+            );
             if (xmlReq.status >= 400) {
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               resolve(xmlReq.responseText);
             }
             return;
 
           case EnigmailConstants.SEARCH_KEY:
             if (xmlReq.status === 404) {
               // key not found
               resolve("");
-            }
-            else if (xmlReq.status >= 400) {
+            } else if (xmlReq.status >= 400) {
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               resolve(xmlReq.responseText);
             }
             return;
 
           case EnigmailConstants.DOWNLOAD_KEY:
             if (xmlReq.status >= 400 && xmlReq.status < 500) {
               // key not found
               resolve(1);
-            }
-            else if (xmlReq.status >= 500) {
-              EnigmailLog.DEBUG("keyserver.jsm: accessVksServer.onload: " + xmlReq.responseText + "\n");
+            } else if (xmlReq.status >= 500) {
+              EnigmailLog.DEBUG(
+                "keyserver.jsm: accessVksServer.onload: " +
+                  xmlReq.responseText +
+                  "\n"
+              );
               reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_ERROR));
-            }
-            else {
+            } else {
               let errorMsgObj = {},
                 importedKeysObj = {};
-              let r = EnigmailKeyRing.importKey(null, false, xmlReq.responseText, "", errorMsgObj, importedKeysObj);
+              let r = EnigmailKeyRing.importKey(
+                null,
+                false,
+                xmlReq.responseText,
+                "",
+                errorMsgObj,
+                importedKeysObj
+              );
               if (r === 0) {
                 resolve(importedKeysObj.value);
-              }
-              else {
-                reject(createError(EnigmailConstants.KEYSERVER_ERR_IMPORT_ERROR));
+              } else {
+                reject(
+                  createError(EnigmailConstants.KEYSERVER_ERR_IMPORT_ERROR)
+                );
               }
             }
             return;
         }
         resolve(-1);
       };
 
       xmlReq.onerror = function(e) {
-        EnigmailLog.DEBUG("keyserver.jsm: accessVksServer.accessKeyServer: onerror: " + e + "\n");
+        EnigmailLog.DEBUG(
+          "keyserver.jsm: accessVksServer.accessKeyServer: onerror: " + e + "\n"
+        );
         let err = EnigmailXhrUtils.createTCPErrorFromFailedXHR(e.target);
         switch (err.type) {
-          case 'SecurityCertificate':
-            reject(createError(EnigmailConstants.KEYSERVER_ERR_CERTIFICATE_ERROR));
+          case "SecurityCertificate":
+            reject(
+              createError(EnigmailConstants.KEYSERVER_ERR_CERTIFICATE_ERROR)
+            );
             break;
-          case 'SecurityProtocol':
+          case "SecurityProtocol":
             reject(createError(EnigmailConstants.KEYSERVER_ERR_SECURITY_ERROR));
             break;
-          case 'Network':
-            reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE));
+          case "Network":
+            reject(
+              createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE)
+            );
             break;
         }
         reject(createError(EnigmailConstants.KEYSERVER_ERR_SERVER_UNAVAILABLE));
       };
 
       xmlReq.onloadend = function() {
-        EnigmailLog.DEBUG("keyserver.jsm: accessVksServer.accessKeyServer: loadEnd\n");
+        EnigmailLog.DEBUG(
+          "keyserver.jsm: accessVksServer.accessKeyServer: loadEnd\n"
+        );
       };
 
-      let {
-        url,
-        host,
-        method,
-        contentType
-      } = this.createRequestUrl(keyserver, actionFlag, keyId);
+      let { url, method, contentType } = this.createRequestUrl(
+        keyserver,
+        actionFlag,
+        keyId
+      );
 
-      EnigmailLog.DEBUG(`keyserver.jsm: accessVksServer.accessKeyServer: requesting ${method} for ${url}\n`);
+      EnigmailLog.DEBUG(
+        `keyserver.jsm: accessVksServer.accessKeyServer: requesting ${method} for ${url}\n`
+      );
       xmlReq.open(method, url);
       xmlReq.setRequestHeader("Content-Type", contentType);
       xmlReq.send(payLoad);
     });
   },
 
   /**
    * Download keys from a keyserver
    * @param keyIDs:      String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<...>
    */
-  download: async function(keyIDs, keyserver, listener = null) {
+  async download(keyIDs, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessVksServer.download(${keyIDs})\n`);
     let keyIdArr = keyIDs.split(/ +/);
     let retObj = {
       result: 0,
       errorDetails: "",
-      keyList: []
+      keyList: [],
     };
 
     for (let i = 0; i < keyIdArr.length; i++) {
       try {
-        let r = await this.accessKeyServer(EnigmailConstants.DOWNLOAD_KEY, keyserver, keyIdArr[i], listener);
+        let r = await this.accessKeyServer(
+          EnigmailConstants.DOWNLOAD_KEY,
+          keyserver,
+          keyIdArr[i],
+          listener
+        );
         if (Array.isArray(r)) {
           retObj.keyList = retObj.keyList.concat(r);
         }
-      }
-      catch (ex) {
+      } catch (ex) {
         retObj.result = ex.result;
         retObj.errorDetails = ex.errorDetails;
         throw retObj;
       }
 
       if (listener && "onProgress" in listener) {
-        listener.onProgress((i + 1) / keyIdArr.length * 100);
+        listener.onProgress(((i + 1) / keyIdArr.length) * 100);
       }
     }
 
     return retObj;
   },
 
-  refresh: function(keyServer, listener = null) {
-    let keyList = EnigmailKeyRing.getAllKeys().keyList.map(keyObj => {
-      return "0x" + keyObj.fpr;
-    }).join(" ");
+  refresh(keyServer, listener = null) {
+    let keyList = EnigmailKeyRing.getAllKeys()
+      .keyList.map(keyObj => {
+        return "0x" + keyObj.fpr;
+      })
+      .join(" ");
 
     return this.download(keyList, keyServer, listener);
   },
 
-  requestConfirmationLink: async function(keyserver, jsonFragment) {
-    EnigmailLog.DEBUG(`keyserver.jsm: accessVksServer.requestConfirmationLink()\n`);
+  async requestConfirmationLink(keyserver, jsonFragment) {
+    EnigmailLog.DEBUG(
+      `keyserver.jsm: accessVksServer.requestConfirmationLink()\n`
+    );
 
     let response = JSON.parse(jsonFragment);
 
     let addr = [];
 
     for (let email in response.status) {
       if (response.status[email] !== "published") {
         addr.push(email);
       }
     }
 
     if (addr.length > 0) {
-      let r = await this.accessKeyServer(EnigmailConstants.GET_CONFIRMATION_LINK, keyserver, {
-        token: response.token,
-        addresses: addr
-      }, null);
+      let r = await this.accessKeyServer(
+        EnigmailConstants.GET_CONFIRMATION_LINK,
+        keyserver,
+        {
+          token: response.token,
+          addresses: addr,
+        },
+        null
+      );
 
       if (typeof r === "string") {
         return addr.length;
       }
     }
 
     return 0;
   },
@@ -1409,58 +1570,61 @@ const accessVksServer = {
   /**
    * Upload keys to a keyserver
    * @param keyIDs: String  - space-separated list of search terms or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<...>
    */
-  upload: async function(keyIDs, keyserver, listener = null) {
+  async upload(keyIDs, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessVksServer.upload(${keyIDs})\n`);
     let keyIdArr = keyIDs.split(/ +/);
     let retObj = {
       result: 0,
       errorDetails: "",
-      keyList: []
+      keyList: [],
     };
 
     for (let i = 0; i < keyIdArr.length; i++) {
       let keyObj = EnigmailKeyRing.getKeyById(keyIdArr[i]);
 
       if (!keyObj.secretAvailable) {
         // VKS keyservers only accept uploading own keys
         retObj.result = 1;
         retObj.errorDetails = "NO_SECRET_KEY_AVAILABLE";
         throw retObj;
       }
 
       try {
-        let r = await this.accessKeyServer(EnigmailConstants.UPLOAD_KEY, keyserver, keyIdArr[i], listener);
+        let r = await this.accessKeyServer(
+          EnigmailConstants.UPLOAD_KEY,
+          keyserver,
+          keyIdArr[i],
+          listener
+        );
         if (typeof r === "string") {
           retObj.keyList.push(keyIdArr[i]);
           let req = await this.requestConfirmationLink(keyserver, r);
 
           if (req >= 0) {
             retObj.result = 0;
             retObj.numEmails = req;
           }
-        }
-        else {
+        } else {
           retObj.result = r;
         }
-      }
-      catch (ex) {
+      } catch (ex) {
         retObj.result = ex.result;
         retObj.errorDetails = ex.errorDetails;
         throw retObj;
       }
 
       if (listener && "onProgress" in listener) {
-        listener.onProgress((i + 1) / keyIdArr.length * 100);
+        listener.onProgress(((i + 1) / keyIdArr.length) * 100);
       }
     }
 
     return retObj;
   },
 
   /**
    * Search for keys on a keyserver
@@ -1474,90 +1638,94 @@ const accessVksServer = {
    *         PubKeys: Object with:
    *           - keyId: String
    *           - keyLen: String
    *           - keyType: String
    *           - created: String (YYYY-MM-DD)
    *           - status: String: one of ''=valid, r=revoked, e=expired
    *           - uid: Array of Strings with UIDs
    */
-  search: async function(searchTerm, keyserver, listener = null) {
+  async search(searchTerm, keyserver, listener = null) {
     EnigmailLog.DEBUG(`keyserver.jsm: accessVksServer.search(${searchTerm})\n`);
     let retObj = {
       result: 0,
       errorDetails: "",
-      pubKeys: []
+      pubKeys: [],
     };
     let key = null;
 
     let searchArr = searchTerm.split(/ +/);
 
     try {
       for (let i in searchArr) {
-        let r = await this.accessKeyServer(EnigmailConstants.SEARCH_KEY, keyserver, searchArr[i], listener);
+        let r = await this.accessKeyServer(
+          EnigmailConstants.SEARCH_KEY,
+          keyserver,
+          searchArr[i],
+          listener
+        );
 
         const cApi = EnigmailCryptoAPI();
         let keyList = await cApi.getKeyListFromKeyBlock(r);
 
         for (let k in keyList) {
           key = {
             keyId: keyList[k].fpr,
             keyLen: "0",
             keyType: "",
             created: keyList[k].created,
             uid: [keyList[k].name],
-            status: keyList[k].revoke ? "r" : ""
+            status: keyList[k].revoke ? "r" : "",
           };
 
           for (let uid of keyList[k].uids) {
             key.uid.push(uid);
           }
 
           retObj.pubKeys.push(key);
         }
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       retObj.result = ex.result;
       retObj.errorDetails = ex.errorDetails;
       throw retObj;
     }
 
     return retObj;
-  }
+  },
 };
 
 var EnigmailKeyServer = {
   /**
    * Download keys from a keyserver
    * @param keyIDs:      String  - space-separated list of FPRs or key IDs
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<Object>
    *     Object: - result: Number           - result Code (0 = OK),
    *             - keyList: Array of String - imported key FPR
    */
-  download: function(keyIDs, keyserver = null, listener) {
+  download(keyIDs, keyserver = null, listener) {
     let acc = getAccessType(keyserver);
     return acc.download(keyIDs, keyserver, listener);
   },
 
   /**
    * Upload keys to a keyserver
    * @param keyIDs:      String  - space-separated list of key IDs or FPR
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<Object>
    *     Object: - result: Number           - result Code (0 = OK),
    *             - keyList: Array of String - imported key FPR
    */
 
-  upload: function(keyIDs, keyserver = null, listener) {
+  upload(keyIDs, keyserver = null, listener) {
     let acc = getAccessType(keyserver);
     return acc.upload(keyIDs, keyserver, listener);
   },
 
   /**
    * Search keys on a keyserver
    * @param searchString: String - search term. Multiple email addresses can be search by spaces
    * @param keyserver:    String - keyserver URL (optionally incl. protocol)
@@ -1569,26 +1737,26 @@ var EnigmailKeyServer = {
    *         PubKeys: Object with:
    *           - keyId: String
    *           - keyLen: String
    *           - keyType: String
    *           - created: String (YYYY-MM-DD)
    *           - status: String: one of ''=valid, r=revoked, e=expired
    *           - uid: Array of Strings with UIDs
    */
-  search: function(searchString, keyserver = null, listener) {
+  search(searchString, keyserver = null, listener) {
     let acc = getAccessType(keyserver);
     return acc.search(searchString, keyserver, listener);
   },
 
   /**
    * Refresh all keys
    *
    * @param keyserver:   String  - keyserver URL (optionally incl. protocol)
    * @param listener:    optional Object implementing the KeySrvListener API (above)
    *
    * @return:   Promise<resultStatus> (identical to download)
    */
-  refresh: function(keyserver = null, listener) {
+  refresh(keyserver = null, listener) {
     let acc = getAccessType(keyserver);
     return acc.refresh(keyserver, listener);
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/keyserverUris.jsm
+++ b/mail/extensions/openpgp/content/modules/keyserverUris.jsm
@@ -3,33 +3,34 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailKeyserverURIs"];
 
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
 
 const KEYSERVER_PREF = "keyserver";
 const AUTO_KEYSERVER_SELECTION_PREF = "autoKeyServerSelection";
 
 const supportedProtocols = {
-  "hkps": "443",
-  "hkp": "11371",
-  "ldap": "389"
+  hkps: "443",
+  hkp: "11371",
+  ldap: "389",
 };
 
 function buildUriFor(protocol, keyserver) {
   return {
-    protocol: protocol,
+    protocol,
     domain: keyserver,
-    port: supportedProtocols[protocol]
+    port: supportedProtocols[protocol],
   };
 }
 
 function addUriOptionsForPoolKeyservers(keyserver, uris) {
   if (keyserver === "hkps.pool.sks-keyservers.net") {
     uris.push(buildUriFor("hkps", keyserver));
   }
   if (keyserver === "pool.sks-keyservers.net") {
@@ -37,68 +38,81 @@ function addUriOptionsForPoolKeyservers(
     uris.push(buildUriFor("hkp", keyserver));
   }
 }
 
 function buildUriOptionsFor(keyserver) {
   const uris = [];
   const keyserverProtocolAndDomain = keyserver.split("://");
   const protocolIncluded = keyserverProtocolAndDomain.length === 2;
-  const isPoolKeyserver = ["hkps.pool.sks-keyservers.net", "pool.sks-keyservers.net"].indexOf(keyserver) > -1;
+  const isPoolKeyserver =
+    ["hkps.pool.sks-keyservers.net", "pool.sks-keyservers.net"].indexOf(
+      keyserver
+    ) > -1;
 
   if (isPoolKeyserver) {
     addUriOptionsForPoolKeyservers(keyserver, uris);
-  }
-  else if (protocolIncluded) {
-    uris.push(buildUriFor(keyserverProtocolAndDomain[0].toLowerCase(), keyserverProtocolAndDomain[1]));
-  }
-  else {
+  } else if (protocolIncluded) {
+    uris.push(
+      buildUriFor(
+        keyserverProtocolAndDomain[0].toLowerCase(),
+        keyserverProtocolAndDomain[1]
+      )
+    );
+  } else {
     uris.push(buildUriFor("hkps", keyserver));
     uris.push(buildUriFor("hkp", keyserver));
   }
 
   return uris;
 }
 
 function getDefaultKeyServer() {
   let keyservers = EnigmailPrefs.getPref(KEYSERVER_PREF).split(/\s*[,;]\s*/g);
   return keyservers[0];
 }
 
 function getUserDefinedKeyserverURIs() {
   const keyservers = EnigmailPrefs.getPref(KEYSERVER_PREF).split(/\s*[,;]\s*/g);
-  return EnigmailPrefs.getPref(AUTO_KEYSERVER_SELECTION_PREF) ? [keyservers[0]] : keyservers;
+  return EnigmailPrefs.getPref(AUTO_KEYSERVER_SELECTION_PREF)
+    ? [keyservers[0]]
+    : keyservers;
 }
 
 function combineIntoURI(protocol, domain, port) {
   return protocol + "://" + domain + ":" + port;
 }
 
 function isValidProtocol(uri) {
   return uri.match(/:\/\//) === null || /^(hkps|hkp|ldap):\/\//i.test(uri);
 }
 
 function validProtocolsExist() {
-  const validKeyserverUris = getUserDefinedKeyserverURIs().filter(isValidProtocol);
+  const validKeyserverUris = getUserDefinedKeyserverURIs().filter(
+    isValidProtocol
+  );
   return validKeyserverUris.length > 0;
 }
 
 /**
  * Construct the full URIs for making gpg requests.
  * This takes the specified keyservers and adds the relevant protocol and port.
  * When no specific protocol is defined by the user, 2 URIs will be built, for hkps and hkp.
  *
  * @return array of all URIs to try refreshing keys over
  */
 function buildKeyserverUris() {
-  const uris = getUserDefinedKeyserverURIs().filter(isValidProtocol).map(function(keyserver) {
-    return buildUriOptionsFor(keyserver);
-  }).reduce(function(a, b) {
-    return a.concat(b);
-  });
+  const uris = getUserDefinedKeyserverURIs()
+    .filter(isValidProtocol)
+    .map(function(keyserver) {
+      return buildUriOptionsFor(keyserver);
+    })
+    .reduce(function(a, b) {
+      return a.concat(b);
+    });
 
   return uris.map(function(uri) {
     return combineIntoURI(uri.protocol, uri.domain, uri.port);
   });
 }
 
 /**
  * Checks if the keyservers specified are valid.
@@ -106,16 +120,18 @@ function buildKeyserverUris() {
  * A valid keyserver is one that is non-empty and consists of
  * - the keyserverDomain
  * - may include a protocol from hkps, hkp or ldap
  * - may include the port
  *
  * @return true if keyservers exist and are valid, false otherwise.
  */
 function validKeyserversExist() {
-  return EnigmailPrefs.getPref(KEYSERVER_PREF).trim() !== "" && validProtocolsExist();
+  return (
+    EnigmailPrefs.getPref(KEYSERVER_PREF).trim() !== "" && validProtocolsExist()
+  );
 }
 
 var EnigmailKeyserverURIs = {
-  getDefaultKeyServer: getDefaultKeyServer,
-  buildKeyserverUris: buildKeyserverUris,
-  validKeyserversExist: validKeyserversExist
+  getDefaultKeyServer,
+  buildKeyserverUris,
+  validKeyserversExist,
 };
--- a/mail/extensions/openpgp/content/modules/lazy.jsm
+++ b/mail/extensions/openpgp/content/modules/lazy.jsm
@@ -3,29 +3,28 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailLazy"];
 
-
 var EnigmailLazy = {
-  loader: function(component, name) {
+  loader(component, name) {
     let holder = null;
     return function() {
       if (holder === null) {
         component = component.replace(/^enigmail\//, "");
         let url;
         try {
           url = "chrome://openpgp/content/modules/" + component;
           const into = ChromeUtils.import(url);
           holder = into[name];
         } catch (ex) {
           console.log(ex);
           console.log("lazy loading couldn't get " + url);
         }
       }
       return holder;
     };
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/locale.jsm
+++ b/mail/extensions/openpgp/content/modules/locale.jsm
@@ -3,104 +3,124 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailLocale"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
 
 var gEnigStringBundle = null;
 
 var EnigmailLocale = {
   /**
    * Get the application locale. Discrecommended - use getUILocale instead!
    */
-  get: function() {
-    try {      
-      return Cc["@mozilla.org/intl/nslocaleservice;1"].getService(Ci.nsILocaleService).getApplicationLocale();
+  get() {
+    try {
+      return Cc["@mozilla.org/intl/nslocaleservice;1"]
+        .getService(Ci.nsILocaleService)
+        .getApplicationLocale();
     } catch (ex) {
       return {
-        getCategory: function(whatever) {
+        getCategory(whatever) {
           // always return the application locale
           try {
             // TB < 64
-            return Cc["@mozilla.org/intl/localeservice;1"].getService(Ci.mozILocaleService).getAppLocaleAsBCP47();
+            return Services.locale.getAppLocaleAsBCP47();
           } catch (x) {
-            let a = Cc["@mozilla.org/intl/localeservice;1"].getService(Ci.mozILocaleService).appLocalesAsBCP47;
-            return (a.length > 0 ? a[0] : "");
+            let a = Services.locale.appLocalesAsBCP47;
+            return a.length > 0 ? a[0] : "";
           }
-        }
+        },
       };
     }
   },
 
   /**
    * Retrieve a localized string from the enigmail.properties stringbundle
    *
    * @param aStr:       String                     - properties key
    * @param subPhrases: String or Array of Strings - [Optional] additional input to be embedded
    *                                                  in the resulting localized text
    *
    * @return String: the localized string
    */
-  getString: function(aStr, subPhrases) {
+  getString(aStr, subPhrases) {
     if (!gEnigStringBundle) {
       try {
         let bundlePath = "chrome://openpgp/content/strings/enigmail.properties";
-        EnigmailLog.DEBUG("locale.jsm: loading stringBundle " + bundlePath + "\n");
-        let strBundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
+        EnigmailLog.DEBUG(
+          "locale.jsm: loading stringBundle " + bundlePath + "\n"
+        );
+        let strBundleService = Services.strings;
         gEnigStringBundle = strBundleService.createBundle(bundlePath);
       } catch (ex) {
-        EnigmailLog.ERROR("locale.jsm: Error in instantiating stringBundleService\n");
+        EnigmailLog.ERROR(
+          "locale.jsm: Error in instantiating stringBundleService\n"
+        );
       }
     }
 
     if (gEnigStringBundle) {
       try {
         let rv;
         if (subPhrases) {
-          if (typeof (subPhrases) == "string") {
+          if (typeof subPhrases == "string") {
             rv = gEnigStringBundle.formatStringFromName(aStr, [subPhrases], 1);
+          } else {
+            rv = gEnigStringBundle.formatStringFromName(
+              aStr,
+              subPhrases,
+              subPhrases.length
+            );
           }
-          else {
-            rv = gEnigStringBundle.formatStringFromName(aStr, subPhrases, subPhrases.length);
-          }
-        }
-        else {
+        } else {
           rv = gEnigStringBundle.GetStringFromName(aStr);
         }
         EnigmailLog.DEBUG("locale.jsm: successfully loaded " + aStr + "\n");
         return rv;
       } catch (ex) {
-        EnigmailLog.ERROR("locale.jsm: Error in querying stringBundleService for string '" + aStr + "', " + ex + "\n");
+        EnigmailLog.ERROR(
+          "locale.jsm: Error in querying stringBundleService for string '" +
+            aStr +
+            "', " +
+            ex +
+            "\n"
+        );
       }
     }
     return aStr;
   },
 
   /**
    * Get the locale for the User Interface
    *
    * @return String  Locale (xx-YY)
    */
-  getUILocale: function() {
-    let ps = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);
+  getUILocale() {
+    let ps = Services.prefs;
     let uaPref = ps.getBranch("general.useragent.");
 
     try {
       return uaPref.getComplexValue("locale", Ci.nsISupportsString).data;
     } catch (e) {}
-    return this.get().getCategory("NSILOCALE_MESSAGES").substr(0, 5);
+    return this.get()
+      .getCategory("NSILOCALE_MESSAGES")
+      .substr(0, 5);
   },
 
-  shutdown: function(reason) {
+  shutdown(reason) {
     // flush string bundles on shutdown of the addon, such that it's no longer cached
     try {
       gEnigStringBundle = null;
-      let strBundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
+      let strBundleService = Services.strings;
       strBundleService.flushBundles();
     } catch (e) {}
-  }
+  },
 };
deleted file mode 100644
--- a/mail/extensions/openpgp/content/modules/localizeHtml.jsm
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-"use strict";
-
-var EXPORTED_SYMBOLS = ["EnigmailLocalizeHtml"];
-
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailBuildDate = ChromeUtils.import("chrome://openpgp/content/modules/buildDate.jsm").EnigmailBuildDate;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
-
-function getEnigmailVersion() {
-  let versionStr = EnigmailApp.getVersion() + " (" + EnigmailBuildDate.built + ")";
-  return EnigmailLocale.getString("usingVersion", versionStr);
-}
-
-var EnigmailLocalizeHtml = {
-  getAllElementsWithAttribute: function(doc, attribute) {
-    let matchingElements = [];
-    let allElements = doc.getElementsByTagName('*');
-    for (let i = 0, n = allElements.length; i < n; i++) {
-      if (allElements[i].getAttribute(attribute) !== null) {
-        matchingElements.push(allElements[i]);
-      }
-    }
-    return matchingElements;
-  },
-
-  onPageLoad: function(doc) {
-    let elem = this.getAllElementsWithAttribute(doc, "txtId");
-
-    for (let i = 0; i < elem.length; i++) {
-      let node = elem[i];
-      let txtId = node.getAttribute("txtId");
-      let param = node.getAttribute("txtParam");
-
-      switch (txtId) {
-        case "FNC_enigmailVersion":
-          node.innerHTML = "no version";
-          break;
-        case "FNC_isGpgWorking":
-          node.innerHTML = "no agent";
-          break;
-        default:
-          node.innerHTML = EnigmailLocale.getString(txtId, param);
-      }
-
-    }
-  }
-};
--- a/mail/extensions/openpgp/content/modules/log.jsm
+++ b/mail/extensions/openpgp/content/modules/log.jsm
@@ -5,165 +5,218 @@
  */
 
 /* global dump: false */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailLog"];
 
-const EnigmailConsole = ChromeUtils.import("chrome://openpgp/content/modules/pipeConsole.jsm").EnigmailConsole;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const XPCOM_APPINFO = "@mozilla.org/xre/app-info;1";
-const NS_IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
+const EnigmailConsole = ChromeUtils.import(
+  "chrome://openpgp/content/modules/pipeConsole.jsm"
+).EnigmailConsole;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
 
 const MAX_LOG_LEN = 2500;
 
 var EnigmailLog = {
   level: 3,
   data: null,
   directory: null,
   fileStream: null,
 
-  setLogLevel: function(newLogLevel) {
+  setLogLevel(newLogLevel) {
     EnigmailLog.level = newLogLevel;
   },
 
-  getLogLevel: function() {
+  getLogLevel() {
     return EnigmailLog.level;
   },
 
-  setLogDirectory: function(newLogDirectory) {
-    EnigmailLog.directory = newLogDirectory + (EnigmailOS.isDosLike ? "\\" : "/");
+  setLogDirectory(newLogDirectory) {
+    EnigmailLog.directory =
+      newLogDirectory + (EnigmailOS.isDosLike ? "\\" : "/");
     EnigmailLog.createLogFiles();
   },
 
-  createLogFiles: function() {
-    if (EnigmailLog.directory && (!EnigmailLog.fileStream) && EnigmailLog.level >= 5) {
-      EnigmailLog.fileStream = EnigmailFiles.createFileStream(EnigmailLog.directory + "enigdbug.txt");
+  createLogFiles() {
+    if (
+      EnigmailLog.directory &&
+      !EnigmailLog.fileStream &&
+      EnigmailLog.level >= 5
+    ) {
+      EnigmailLog.fileStream = EnigmailFiles.createFileStream(
+        EnigmailLog.directory + "enigdbug.txt"
+      );
     }
   },
 
-  onShutdown: function() {
+  onShutdown() {
     if (EnigmailLog.fileStream) {
       EnigmailLog.fileStream.close();
     }
     EnigmailLog.fileStream = null;
   },
 
-  getLogData: function(version, prefs) {
-    let ioServ = Cc[NS_IOSERVICE_CONTRACTID].getService(Ci.nsIIOService);
+  getLogData(version, prefs) {
+    let ioServ = Services.io;
 
     let oscpu = "";
     let platform = "";
 
     try {
       let httpHandler = ioServ.getProtocolHandler("http");
       httpHandler = httpHandler.QueryInterface(Ci.nsIHttpProtocolHandler);
       oscpu = httpHandler.oscpu;
       platform = httpHandler.platform;
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
-    let data = "Enigmail version " + version + "\n" +
-      "OS/CPU=" + oscpu + "\n" +
-      "Platform=" + platform + "\n" +
+    let data =
+      "Enigmail version " +
+      version +
+      "\n" +
+      "OS/CPU=" +
+      oscpu +
+      "\n" +
+      "Platform=" +
+      platform +
+      "\n" +
       "Non-default preference values:\n";
 
     let p = prefs.getPrefBranch().getChildList("");
 
     for (let i in p) {
       if (prefs.getPrefBranch().prefHasUserValue(p[i])) {
         data += p[i] + ": " + prefs.getPref(p[i]) + "\n";
       }
     }
 
     let otherPref = ["dom.workers.maxPerDomain"];
     let root = prefs.getPrefRoot();
     for (let op of otherPref) {
       try {
         data += op + ": " + root.getIntPref(op) + "\n";
-      }
-      catch (ex) {
+      } catch (ex) {
         data += ex.toString() + "\n";
       }
     }
     return data + "\n" + EnigmailLog.data.join("");
   },
 
-  WRITE: function(str) {
+  WRITE(str) {
     function withZeroes(val, digits) {
       return ("0000" + val.toString()).substr(-digits);
     }
 
     var d = new Date();
-    var datStr = d.getFullYear() + "-" + withZeroes(d.getMonth() + 1, 2) + "-" + withZeroes(d.getDate(), 2) + " " + withZeroes(d.getHours(), 2) + ":" + withZeroes(d.getMinutes(), 2) + ":" +
-      withZeroes(d.getSeconds(), 2) + "." + withZeroes(d.getMilliseconds(), 3) + " ";
-    if (EnigmailLog.level >= 4)
+    var datStr =
+      d.getFullYear() +
+      "-" +
+      withZeroes(d.getMonth() + 1, 2) +
+      "-" +
+      withZeroes(d.getDate(), 2) +
+      " " +
+      withZeroes(d.getHours(), 2) +
+      ":" +
+      withZeroes(d.getMinutes(), 2) +
+      ":" +
+      withZeroes(d.getSeconds(), 2) +
+      "." +
+      withZeroes(d.getMilliseconds(), 3) +
+      " ";
+    if (EnigmailLog.level >= 4) {
       dump(datStr + str);
+    }
 
     if (EnigmailLog.data === null) {
       EnigmailLog.data = [];
-      let appInfo = Cc[XPCOM_APPINFO].getService(Ci.nsIXULAppInfo);
-      EnigmailLog.WRITE("Mozilla Platform: " + appInfo.name + " " + appInfo.version + "\n");
+      let appInfo = Services.appinfo;
+      EnigmailLog.WRITE(
+        "Mozilla Platform: " + appInfo.name + " " + appInfo.version + "\n"
+      );
     }
     // truncate first part of log data if it grow too much
     if (EnigmailLog.data.length > MAX_LOG_LEN) {
       EnigmailLog.data.splice(0, 200);
     }
 
     EnigmailLog.data.push(datStr + str);
 
     if (EnigmailLog.fileStream) {
       EnigmailLog.fileStream.write(datStr, datStr.length);
       EnigmailLog.fileStream.write(str, str.length);
     }
   },
 
-  DEBUG: function(str) {
+  DEBUG(str) {
     try {
       EnigmailLog.WRITE("[DEBUG] " + str);
-    }
-    catch (ex) {}
+    } catch (ex) {}
   },
 
-  WARNING: function(str) {
+  WARNING(str) {
     EnigmailLog.WRITE("[WARN] " + str);
     EnigmailConsole.write(str);
   },
 
-  ERROR: function(str) {
+  ERROR(str) {
     try {
-      var consoleSvc = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
-      var scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(Ci.nsIScriptError);
-      scriptError.init(str, null, null, 0, 0, scriptError.errorFlag, "Enigmail");
+      var consoleSvc = Services.console;
+      var scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(
+        Ci.nsIScriptError
+      );
+      scriptError.init(
+        str,
+        null,
+        null,
+        0,
+        0,
+        scriptError.errorFlag,
+        "Enigmail"
+      );
       consoleSvc.logMessage(scriptError);
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     EnigmailLog.WRITE("[ERROR] " + str);
   },
 
-  CONSOLE: function(str) {
+  CONSOLE(str) {
     if (EnigmailLog.level >= 3) {
       EnigmailLog.WRITE("[CONSOLE] " + str);
     }
 
     EnigmailConsole.write(str);
   },
 
   /**
    *  Log an exception including the stack trace
    *
    *  referenceInfo: String - arbitraty text to write before the exception is logged
    *  ex:            exception object
    */
-  writeException: function(referenceInfo, ex) {
-    EnigmailLog.ERROR(referenceInfo + ": caught exception: " +
-      ex.name + "\n" +
-      "Message: '" + ex.message + "'\n" +
-      "File:    " + ex.fileName + "\n" +
-      "Line:    " + ex.lineNumber + "\n" +
-      "Stack:   " + ex.stack + "\n");
-  }
+  writeException(referenceInfo, ex) {
+    EnigmailLog.ERROR(
+      referenceInfo +
+        ": caught exception: " +
+        ex.name +
+        "\n" +
+        "Message: '" +
+        ex.message +
+        "'\n" +
+        "File:    " +
+        ex.fileName +
+        "\n" +
+        "Line:    " +
+        ex.lineNumber +
+        "\n" +
+        "Stack:   " +
+        ex.stack +
+        "\n"
+    );
+  },
 };
--- a/mail/extensions/openpgp/content/modules/masterpass.jsm
+++ b/mail/extensions/openpgp/content/modules/masterpass.jsm
@@ -1,82 +1,105 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
- 
+
 /*global Components: false */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["OpenPGPMasterpass"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
+Cu.importGlobalProperties(["crypto"]);
+
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const PASS_URI = 'chrome://openpgp-secret-key-password';
-const PASS_REALM = 'DO NOT DELETE';
-const PASS_USER = 'openpgp';
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+
+const PASS_URI = "chrome://openpgp-secret-key-password";
+const PASS_REALM = "DO NOT DELETE";
+const PASS_USER = "openpgp";
 
 var OpenPGPMasterpass = {
-  getLoginManager: function() {
+  getLoginManager() {
     if (!this.loginManager) {
       try {
-        this.loginManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
+        this.loginManager = Services.logins;
       } catch (ex) {
         EnigmailLog.writeException("masterpass.jsm", ex);
       }
     }
     return this.loginManager;
   },
 
-  ensureMasterPassword: function() {
+  ensureMasterPassword() {
     let password = this.retrieveOpenPGPPassword();
     if (password) {
       return;
     }
 
     try {
       let pass = this.generatePassword();
 
       EnigmailLog.DEBUG("masterpass.jsm: ensureMasterPassword()\n");
-      let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo, "init");
+      let nsLoginInfo = new Components.Constructor(
+        "@mozilla.org/login-manager/loginInfo;1",
+        Ci.nsILoginInfo,
+        "init"
+      );
       // parameters: aHostname, aFormSubmitURL, aHttpRealm, aUsername, aPassword, aUsernameField, aPasswordField
-      let loginInfo = new nsLoginInfo(PASS_URI, null, PASS_REALM, PASS_USER, pass, '', '');
+      let loginInfo = new nsLoginInfo(
+        PASS_URI,
+        null,
+        PASS_REALM,
+        PASS_USER,
+        pass,
+        "",
+        ""
+      );
 
       this.getLoginManager().addLogin(loginInfo);
     } catch (ex) {
       EnigmailLog.writeException("masterpass.jsm", ex);
       throw ex;
     }
     EnigmailLog.DEBUG("masterpass.jsm: ensureMasterPassword(): ok\n");
   },
 
-  generatePassword: function() {
+  generatePassword() {
     // TODO: Patrick suggested to replace with
     //       EnigmailRNG.getRandomString(numChars)
     const random_bytes = new Uint8Array(32);
     crypto.getRandomValues(random_bytes);
     let result = "";
     for (let i = 0; i < 32; i++) {
       result += (random_bytes[i] % 16).toString(16);
     }
     return result;
   },
 
-  retrieveOpenPGPPassword: function() {
+  retrieveOpenPGPPassword() {
     EnigmailLog.DEBUG("masterpass.jsm: retrieveMasterPassword()\n");
     try {
-      var logins = this.getLoginManager().findLogins(PASS_URI, null, PASS_REALM);
+      var logins = this.getLoginManager().findLogins(
+        PASS_URI,
+        null,
+        PASS_REALM
+      );
 
       for (let i = 0; i < logins.length; i++) {
         if (logins[i].username == PASS_USER) {
           EnigmailLog.DEBUG("masterpass.jsm: retrieveOpenPGPPassword(): ok\n");
           return logins[i].password;
         }
       }
     } catch (ex) {
       EnigmailLog.writeException("masterpass.jsm", ex);
     }
     EnigmailLog.DEBUG("masterpass.jsm: retrieveMasterPassword(): not found!\n");
     return null;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/mime.jsm
+++ b/mail/extensions/openpgp/content/modules/mime.jsm
@@ -4,94 +4,102 @@
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailMime"];
 
 const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailRNG = ChromeUtils.import("chrome://openpgp/content/modules/rng.jsm").EnigmailRNG;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailRNG = ChromeUtils.import(
+  "chrome://openpgp/content/modules/rng.jsm"
+).EnigmailRNG;
+const EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
 
 var EnigmailMime = {
   /***
    * create a string of random characters suitable to use for a boundary in a
    * MIME message following RFC 2045
    *
    * @return: string of 33 random characters and digits
    */
-  createBoundary: function() {
+  createBoundary() {
     return EnigmailRNG.generateRandomString(33);
   },
 
   /***
    * determine the "boundary" part of a mail content type.
    *
    * @contentTypeStr: the string containing all parts of a content-type.
    *               (e.g. multipart/mixed; boundary="xyz") --> returns "xyz"
    *
    * @return: String containing the boundary parameter; or ""
    */
 
-  getBoundary: function(contentTypeStr) {
+  getBoundary(contentTypeStr) {
     return EnigmailMime.getParameter(contentTypeStr, "boundary");
   },
 
   /***
    * determine the "protocol" part of a mail content type.
    *
    * @contentTypeStr: the string containing all parts of a content-type.
    *               (e.g. multipart/signed; protocol="xyz") --> returns "xyz"
    *
    * @return: String containing the protocol parameter; or ""
    */
 
-  getProtocol: function(contentTypeStr) {
+  getProtocol(contentTypeStr) {
     return EnigmailMime.getParameter(contentTypeStr, "protocol");
   },
 
   /***
    * determine an arbitrary "parameter" part of a mail header.
    *
    * @param headerStr: the string containing all parts of the header.
    * @param parameter: the parameter we are looking for
    *
    *
    * 'multipart/signed; protocol="xyz"', 'protocol' --> returns "xyz"
    *
    * @return: String containing the parameter; or ""
    */
 
-  getParameter: function(headerStr, parameter) {
+  getParameter(headerStr, parameter) {
     let paramsArr = EnigmailMime.getAllParameters(headerStr);
     parameter = parameter.toLowerCase();
     if (parameter in paramsArr) {
       return paramsArr[parameter];
     }
-    else
-      return "";
+    return "";
   },
 
   /***
    * get all parameter attributes of a mail header.
    *
    * @param headerStr: the string containing all parts of the header.
    *
    * @return: Array of Object containing the key value pairs
    *
    * 'multipart/signed; protocol="xyz"'; boundary="xxx"
    *  --> returns [ ["protocol": "xyz"], ["boundary": "xxx"] ]
    */
 
-  getAllParameters: function(headerStr) {
-
+  getAllParameters(headerStr) {
     headerStr = headerStr.replace(/[\r\n]+[ \t]+/g, "");
-    let hdrMap = jsmime.headerparser.parseParameterHeader(";" + headerStr, true, true);
+    let hdrMap = jsmime.headerparser.parseParameterHeader(
+      ";" + headerStr,
+      true,
+      true
+    );
 
     let paramArr = [];
     let i = hdrMap.entries();
     let p = i.next();
     while (p.value) {
       paramArr[p.value[0].toLowerCase()] = p.value[1];
       p = i.next();
     }
@@ -103,81 +111,80 @@ var EnigmailMime = {
    * determine the "charset" part of a mail content type.
    *
    * @contentTypeStr: the string containing all parts of a content-type.
    *               (e.g. multipart/mixed; charset="utf-8") --> returns "utf-8"
    *
    * @return: String containing the charset parameter; or null
    */
 
-  getCharset: function(contentTypeStr) {
+  getCharset(contentTypeStr) {
     return EnigmailMime.getParameter(contentTypeStr, "charset");
   },
 
   /**
    * Convert a MIME header value into a UTF-8 encoded representation following RFC 2047
    */
-  encodeHeaderValue: function(aStr) {
+  encodeHeaderValue(aStr) {
     let ret = "";
 
-    if (aStr.search(/[^\x01-\x7F]/) >= 0) { // eslint-disable-line no-control-regex
+    let exp = /[^\x01-\x7F]/; // eslint-disable-line no-control-regex
+    if (aStr.search(exp) >= 0) {
       let s = EnigmailData.convertFromUnicode(aStr, "utf-8");
       ret = "=?UTF-8?B?" + btoa(s) + "?=";
-    }
-    else {
+    } else {
       ret = aStr;
     }
 
     return ret;
   },
 
   /**
    * format MIME header with maximum length of 72 characters.
    */
-  formatHeaderData: function(hdrValue) {
+  formatHeaderData(hdrValue) {
     let header;
     if (Array.isArray(hdrValue)) {
       header = hdrValue.join("").split(" ");
-    }
-    else {
+    } else {
       header = hdrValue.split(/ +/);
     }
 
     let line = "";
     let lines = [];
 
     for (let i = 0; i < header.length; i++) {
       if (line.length + header[i].length >= 72) {
         lines.push(line + "\r\n");
         line = " " + header[i];
-      }
-      else {
+      } else {
         line += " " + header[i];
       }
     }
 
     lines.push(line);
 
     return lines.join("").trim();
   },
 
   /**
    * Correctly encode and format a set of email addresses for RFC 2047
    */
-  formatEmailAddress: function(addressData) {
+  formatEmailAddress(addressData) {
     const adrArr = addressData.split(/, */);
 
     for (let i in adrArr) {
       try {
-        const m = adrArr[i].match(/(.*[\w\s]+?)<([\w-][\w.-]+@[\w-][\w.-]+[a-zA-Z]{1,4})>/);
+        const m = adrArr[i].match(
+          /(.*[\w\s]+?)<([\w-][\w.-]+@[\w-][\w.-]+[a-zA-Z]{1,4})>/
+        );
         if (m && m.length == 3) {
           adrArr[i] = this.encodeHeaderValue(m[1]) + " <" + m[2] + ">";
         }
-      }
-      catch (ex) {}
+      } catch (ex) {}
     }
 
     return adrArr.join(", ");
   },
 
   /**
    * Extract the subject from the 1st line of the message body, if the message body starts
    * with: "Subject: ...\r?\n\r?\n".
@@ -187,67 +194,80 @@ var EnigmailMime = {
    * @return
    * if subject is found:
    *  Object:
    *    - messageBody - String: message body without subject
    *    - subject     - String: extracted subject
    *
    * if subject not found: null
    */
-  extractSubjectFromBody: function(msgBody) {
+  extractSubjectFromBody(msgBody) {
     let m = msgBody.match(/^(\r?\n?Subject: [^\r\n]+\r?\n\r?\n)/i);
     if (m && m.length > 0) {
       let subject = m[0].replace(/[\r\n]/g, "");
       subject = subject.substr(9);
       msgBody = msgBody.substr(m[0].length);
 
       return {
         messageBody: msgBody,
-        subject: subject
+        subject,
       };
     }
 
     return null;
   },
 
   /***
    * determine if the message data contains a first mime part with content-type = "text/rfc822-headers"
    * if so, extract the corresponding field(s)
    */
 
-  extractProtectedHeaders: function(contentData) {
+  extractProtectedHeaders(contentData) {
     // find first MIME delimiter. Anything before that delimiter is the top MIME structure
     let m = contentData.search(/^--/m);
 
-    let protectedHdr = ["subject", "date", "from",
-      "to", "cc", "reply-to", "references",
-      "newsgroups", "followup-to", "message-id"
+    let protectedHdr = [
+      "subject",
+      "date",
+      "from",
+      "to",
+      "cc",
+      "reply-to",
+      "references",
+      "newsgroups",
+      "followup-to",
+      "message-id",
     ];
     let newHeaders = {};
 
     // read headers of first MIME part and extract the boundary parameter
-    let outerHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let outerHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     outerHdr.initialize(contentData.substr(0, m));
 
     let ct = outerHdr.extractHeader("content-type", false) || "";
-    if (ct === "") return null;
+    if (ct === "") {
+      return null;
+    }
 
     let startPos = -1,
       endPos = -1,
       bound = "";
 
     if (ct.search(/^multipart\//i) === 0) {
       // multipart/xyz message type
       if (m < 5) {
         return null;
       }
 
-
       bound = EnigmailMime.getBoundary(ct);
-      if (bound === "") return null;
+      if (bound === "") {
+        return null;
+      }
 
       // search for "outer" MIME delimiter(s)
       let r = new RegExp("^--" + bound, "mg");
 
       startPos = -1;
       endPos = -1;
 
       // 1st match: start of 1st MIME-subpart
@@ -257,103 +277,118 @@ var EnigmailMime = {
       }
 
       // 2nd  match: end of 1st MIME-subpart
       match = r.exec(contentData);
       if (match && match.index) {
         endPos = match.index;
       }
 
-      if (startPos < 0 || endPos < 0) return null;
-    }
-    else {
+      if (startPos < 0 || endPos < 0) {
+        return null;
+      }
+    } else {
       startPos = contentData.length;
       endPos = 0;
     }
 
-    let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     headers.initialize(contentData.substring(0, startPos));
 
     // we got a potentially protected header. Let's check ...
     ct = headers.extractHeader("content-type", false) || "";
-    if (this.getParameter(ct, "protected-headers").search(/^v1$/i) !== 0) return null;
+    if (this.getParameter(ct, "protected-headers").search(/^v1$/i) !== 0) {
+      return null;
+    }
 
     for (let i in protectedHdr) {
       if (headers.hasHeader(protectedHdr[i])) {
-        newHeaders[protectedHdr[i]] = jsmime.headerparser.decodeRFC2047Words(headers.extractHeader(protectedHdr[i], true)) || undefined;
+        newHeaders[protectedHdr[i]] =
+          jsmime.headerparser.decodeRFC2047Words(
+            headers.extractHeader(protectedHdr[i], true)
+          ) || undefined;
       }
     }
 
     // contentBody holds the complete 1st MIME part
-    let contentBody = contentData.substring(startPos + bound.length + 3, endPos);
+    let contentBody = contentData.substring(
+      startPos + bound.length + 3,
+      endPos
+    );
     let i = contentBody.search(/^[A-Za-z]/m); // skip empty lines
     if (i > 0) {
       contentBody = contentBody.substr(i);
     }
 
     headers.initialize(contentBody);
 
     let innerCt = headers.extractHeader("content-type", false) || "";
 
     if (innerCt.search(/^text\/rfc822-headers/i) === 0) {
-
       let charset = EnigmailMime.getCharset(innerCt);
       let ctt = headers.extractHeader("content-transfer-encoding", false) || "";
 
       // determine where the headers end and the MIME-subpart body starts
       let bodyStartPos = contentBody.search(/\r?\n\s*\r?\n/) + 1;
 
-      if (bodyStartPos < 10) return null;
+      if (bodyStartPos < 10) {
+        return null;
+      }
 
       bodyStartPos += contentBody.substr(bodyStartPos).search(/^[A-Za-z]/m);
 
       let ctBodyData = contentBody.substr(bodyStartPos);
 
       if (ctt.search(/^base64/i) === 0) {
         ctBodyData = EnigmailData.decodeBase64(ctBodyData) + "\n";
-      }
-      else if (ctt.search(/^quoted-printable/i) === 0) {
+      } else if (ctt.search(/^quoted-printable/i) === 0) {
         ctBodyData = EnigmailData.decodeQuotedPrintable(ctBodyData) + "\n";
       }
 
       if (charset) {
         ctBodyData = EnigmailData.convertToUnicode(ctBodyData, charset);
       }
 
       // get the headers of the MIME-subpart body --> that's the ones we need
-      let bodyHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+      let bodyHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+        Ci.nsIMimeHeaders
+      );
       bodyHdr.initialize(ctBodyData);
 
       for (let i in protectedHdr) {
         if (bodyHdr.hasHeader(protectedHdr[i])) {
-          newHeaders[protectedHdr[i]] = jsmime.headerparser.decodeRFC2047Words(bodyHdr.extractHeader(protectedHdr[i], true)) || undefined;
+          newHeaders[protectedHdr[i]] =
+            jsmime.headerparser.decodeRFC2047Words(
+              bodyHdr.extractHeader(protectedHdr[i], true)
+            ) || undefined;
         }
       }
-    }
-    else {
+    } else {
       startPos = -1;
       endPos = -1;
     }
 
     return {
-      newHeaders: newHeaders,
-      startPos: startPos,
-      endPos: endPos,
-      securityLevel: 0
+      newHeaders,
+      startPos,
+      endPos,
+      securityLevel: 0,
     };
   },
 
   /**
    * Get the part number from a URI spec (e.g. mailbox:///folder/xyz?part=1.2.3.5)
    *
    * @param spec: String - the URI spec to inspect
    *
    * @return String: the mime part number (or "" if none found)
    */
-  getMimePartNumber: function(spec) {
+  getMimePartNumber(spec) {
     let m = spec.match(/([\?&]part=)(\d+(\.\d+)*)/);
 
     if (m && m.length >= 3) {
       return m[2];
     }
 
     return "";
   },
@@ -363,64 +398,78 @@ var EnigmailMime = {
    * based on the MIME part number and the uriSpec.
    *
    * @param mimePartNumber: String - the MIME part we are requested to decrypt
    * @param uriSpec:        String - the URI spec of the message (or msg part) loaded by TB
    *
    * @return Boolean: true: regular message structure, MIME part is safe to be decrypted
    *                  false: otherwise
    */
-  isRegularMimeStructure: function(mimePartNumber, uriSpec, acceptSubParts = false) {
-    if (mimePartNumber.length === 0) return true;
+  isRegularMimeStructure(mimePartNumber, uriSpec, acceptSubParts = false) {
+    if (mimePartNumber.length === 0) {
+      return true;
+    }
 
-    if (acceptSubParts && (mimePartNumber.search(/^1(\.1)*$/) === 0)) return true;
-    if (mimePartNumber === "1") return true;
+    if (acceptSubParts && mimePartNumber.search(/^1(\.1)*$/) === 0) {
+      return true;
+    }
+    if (mimePartNumber === "1") {
+      return true;
+    }
 
-    if (!uriSpec) return true;
+    if (!uriSpec) {
+      return true;
+    }
 
     // is the message a subpart of a complete attachment?
     let msgPart = this.getMimePartNumber(uriSpec);
     if (msgPart.length > 0) {
       // load attached messages
-      if (mimePartNumber.indexOf(msgPart) === 0 &&
-        mimePartNumber.substr(msgPart.length).search(/^(\.1)+$/) === 0) return true;
+      if (
+        mimePartNumber.indexOf(msgPart) === 0 &&
+        mimePartNumber.substr(msgPart.length).search(/^(\.1)+$/) === 0
+      ) {
+        return true;
+      }
 
       // load attachments of attached messages
-      if (msgPart.indexOf(mimePartNumber) === 0 &&
-        uriSpec.search(/[\?&]filename=/) > 0) return true;
+      if (
+        msgPart.indexOf(mimePartNumber) === 0 &&
+        uriSpec.search(/[\?&]filename=/) > 0
+      ) {
+        return true;
+      }
     }
 
     return false;
   },
 
-
   /**
    * Parse a MIME message and return a tree structur of TreeObject
    *
    * @param url:         String   - the URL to load and parse
    * @param getBody:     Boolean  - if true, delivers the body text of each MIME part
    * @param callbackFunc Function - the callback function that is called asynchronously
    *                                when parsing is complete.
    *                                Function signature: callBackFunc(TreeObject)
    *
    * @return undefined
    */
-  getMimeTreeFromUrl: function(url, getBody = false, callbackFunc) {
+  getMimeTreeFromUrl(url, getBody = false, callbackFunc) {
     function onData(data) {
       let tree = getMimeTree(data, getBody);
       callbackFunc(tree);
     }
 
     let chan = EnigmailStreams.createChannel(url);
     let bufferListener = EnigmailStreams.newStringStreamListener(onData);
     chan.asyncOpen(bufferListener, null);
   },
 
-  getMimeTree: getMimeTree
-
+  getMimeTree,
 };
 
 /**
  * Parse a MIME message and return a tree structure of TreeObject.
  *
  * TreeObject contains the following main parts:
  *     - partNum: String
  *     - headers: Map, containing all headers.
@@ -429,97 +478,90 @@ var EnigmailMime = {
  *     - subParts: Array of TreeObject
  *
  * @param mimeStr: String  - a MIME structure to parse
  * @param getBody: Boolean - if true, delivers the body text of each MIME part
  *
  * @return TreeObject, or NULL in case of failure
  */
 function getMimeTree(mimeStr, getBody = false) {
-
   let mimeTree = {
       partNum: "",
       headers: null,
       body: "",
       parent: null,
-      subParts: []
+      subParts: [],
     },
-    stack = [],
     currentPart = "",
     currPartNum = "";
 
   const jsmimeEmitter = {
-
-    createPartObj: function(partNum, headers, parent) {
+    createPartObj(partNum, headers, parent) {
       let ct;
 
       if (headers.has("content-type")) {
         ct = headers.contentType.type;
         let it = headers.get("content-type").entries();
         for (let i of it) {
-          ct += '; ' + i[0] + '="' + i[1] + '"';
+          ct += "; " + i[0] + '="' + i[1] + '"';
         }
       }
 
       return {
-        partNum: partNum,
-        headers: headers,
+        partNum,
+        headers,
         fullContentType: ct,
         body: "",
-        parent: parent,
-        subParts: []
+        parent,
+        subParts: [],
       };
     },
 
     /** JSMime API **/
-    startMessage: function() {
+    startMessage() {
       currentPart = mimeTree;
     },
 
-    endMessage: function() {},
+    endMessage() {},
 
-    startPart: function(partNum, headers) {
+    startPart(partNum, headers) {
       //dump("mime.jsm: jsmimeEmitter.startPart: partNum=" + partNum + "\n");
       partNum = "1" + (partNum !== "" ? "." : "") + partNum;
       let newPart = this.createPartObj(partNum, headers, currentPart);
 
       if (partNum.indexOf(currPartNum) === 0) {
         // found sub-part
         currentPart.subParts.push(newPart);
-      }
-      else {
+      } else {
         // found same or higher level
         currentPart.subParts.push(newPart);
       }
       currPartNum = partNum;
       currentPart = newPart;
     },
-    endPart: function(partNum) {
+    endPart(partNum) {
       //dump("mime.jsm: jsmimeEmitter.startPart: partNum=" + partNum + "\n");
       currentPart = currentPart.parent;
     },
 
-    deliverPartData: function(partNum, data) {
+    deliverPartData(partNum, data) {
       //dump("mime.jsm: jsmimeEmitter.deliverPartData: partNum=" + partNum + " / " + typeof data + "\n");
-      if (typeof(data) === "string") {
+      if (typeof data === "string") {
         currentPart.body += data;
-      }
-      else {
+      } else {
         currentPart.body += EnigmailData.arrayBufferToString(data);
       }
-    }
+    },
   };
 
   let opt = {
     strformat: "unicode",
-    bodyformat: getBody ? "decode" : "none"
+    bodyformat: getBody ? "decode" : "none",
   };
 
-
   try {
     let p = new jsmime.MimeParser(jsmimeEmitter, opt);
     p.deliverData(mimeStr);
     return mimeTree.subParts[0];
-  }
-  catch (ex) {
+  } catch (ex) {
     return null;
   }
 }
--- a/mail/extensions/openpgp/content/modules/mimeDecrypt.jsm
+++ b/mail/extensions/openpgp/content/modules/mimeDecrypt.jsm
@@ -6,67 +6,96 @@
 
 var EXPORTED_SYMBOLS = ["EnigmailMimeDecrypt"];
 
 /**
  *  Module for handling PGP/MIME encrypted messages
  *  implemented as an XPCOM object
  */
 
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailVerify = ChromeUtils.import("chrome://openpgp/content/modules/mimeVerify.jsm").EnigmailVerify;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailDecryption = ChromeUtils.import("chrome://openpgp/content/modules/decryption.jsm").EnigmailDecryption;
-var EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailURIs = ChromeUtils.import("chrome://openpgp/content/modules/uris.jsm").EnigmailURIs;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailSingletons = ChromeUtils.import("chrome://openpgp/content/modules/singletons.jsm").EnigmailSingletons;
-const EnigmailHttpProxy = ChromeUtils.import("chrome://openpgp/content/modules/httpProxy.jsm").EnigmailHttpProxy;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
-const EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-
-const APPSHELL_MEDIATOR_CONTRACTID = "@mozilla.org/appshell/window-mediator;1";
-const PGPMIME_JS_DECRYPTOR_CONTRACTID = "@mozilla.org/mime/pgp-mime-js-decrypt;1";
-const PGPMIME_JS_DECRYPTOR_CID = Components.ID("{7514cbeb-2bfd-4b2c-829b-1a4691fa0ac8}");
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailVerify = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mimeVerify.jsm"
+).EnigmailVerify;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailDecryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/decryption.jsm"
+).EnigmailDecryption;
+var EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailURIs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/uris.jsm"
+).EnigmailURIs;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailSingletons = ChromeUtils.import(
+  "chrome://openpgp/content/modules/singletons.jsm"
+).EnigmailSingletons;
+const EnigmailHttpProxy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/httpProxy.jsm"
+).EnigmailHttpProxy;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
+const EnigmailAutocrypt = ChromeUtils.import(
+  "chrome://openpgp/content/modules/autocrypt.jsm"
+).EnigmailAutocrypt;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
 
 const ENCODING_DEFAULT = 0;
 const ENCODING_BASE64 = 1;
 const ENCODING_QP = 2;
 
 const LAST_MSG = EnigmailSingletons.lastDecryptedMessage;
 
 var gDebugLogLevel = 5;
 
 var gNumProc = 0;
 
 var EnigmailMimeDecrypt = {
   /**
    * create a new instance of a PGP/MIME decryption handler
    */
-  newPgpMimeHandler: function() {
+  newPgpMimeHandler() {
     return new MimeDecryptHandler();
   },
 
   /**
    * Return a fake empty attachment with information that the message
    * was not decrypted
    *
    * @return {String}: MIME string (HTML text)
    */
-  emptyAttachment: function() {
+  emptyAttachment() {
     EnigmailLog.DEBUG("mimeDecrypt.jsm: emptyAttachment()\n");
 
-    let encPart = EnigmailLocale.getString("mimeDecrypt.encryptedPart.attachmentLabel");
-    let concealed = EnigmailLocale.getString("mimeDecrypt.encryptedPart.concealedData");
-    let retData =
-      `Content-Type: message/rfc822; name="${encPart}.eml"
+    let encPart = EnigmailLocale.getString(
+      "mimeDecrypt.encryptedPart.attachmentLabel"
+    );
+    let concealed = EnigmailLocale.getString(
+      "mimeDecrypt.encryptedPart.concealedData"
+    );
+    let retData = `Content-Type: message/rfc822; name="${encPart}.eml"
 Content-Transfer-Encoding: 7bit
 Content-Disposition: attachment; filename="${encPart}.eml"
 
 Content-Type: text/html
 
 <p><i>${concealed}</i></p>
 `;
     return retData;
@@ -75,46 +104,56 @@ Content-Type: text/html
   /**
    * Wrap the decrypted output into a message/rfc822 attachment
    *
    * @param {String} decryptingMimePartNum: requested MIME part number
    * @param {Object} uri: nsIURI object of the decrypted message
    *
    * @return {String}: prefix for message data
    */
-  pretendAttachment: function(decryptingMimePartNum, uri) {
-    if (decryptingMimePartNum === "1" || !uri) return "";
+  pretendAttachment(decryptingMimePartNum, uri) {
+    if (decryptingMimePartNum === "1" || !uri) {
+      return "";
+    }
 
     let msg = "";
     let mimePartNumber = EnigmailMime.getMimePartNumber(uri.spec);
 
     if (mimePartNumber === decryptingMimePartNum + ".1") {
-      msg = 'Content-Type: message/rfc822; name="attachment.eml"\r\n' +
-        'Content-Transfer-Encoding: 7bit\r\n' +
+      msg =
+        'Content-Type: message/rfc822; name="attachment.eml"\r\n' +
+        "Content-Transfer-Encoding: 7bit\r\n" +
         'Content-Disposition: attachment; filename="attachment.eml"\r\n\r\n';
 
       try {
         let dbHdr = uri.QueryInterface(Ci.nsIMsgMessageUrl).messageHeader;
-        if (dbHdr.subject) msg += `Subject: ${dbHdr.subject}\r\n`;
-        if (dbHdr.author) msg += `From: ${dbHdr.author}\r\n`;
-        if (dbHdr.recipients) msg += `To: ${dbHdr.recipients}\r\n`;
-        if (dbHdr.ccList) msg += `Cc: ${dbHdr.ccList}\r\n`;
+        if (dbHdr.subject) {
+          msg += `Subject: ${dbHdr.subject}\r\n`;
+        }
+        if (dbHdr.author) {
+          msg += `From: ${dbHdr.author}\r\n`;
+        }
+        if (dbHdr.recipients) {
+          msg += `To: ${dbHdr.recipients}\r\n`;
+        }
+        if (dbHdr.ccList) {
+          msg += `Cc: ${dbHdr.ccList}\r\n`;
+        }
       } catch (x) {}
     }
 
     return msg;
-  }
+  },
 };
 
 ////////////////////////////////////////////////////////////////////
 // handler for PGP/MIME encrypted messages
 // data is processed from libmime -> nsPgpMimeProxy
 
 function MimeDecryptHandler() {
-
   EnigmailLog.DEBUG("mimeDecrypt.jsm: MimeDecryptHandler()\n"); // always log this one
   this.mimeSvc = null;
   this.initOk = false;
   this.boundary = "";
   this.pipe = null;
   this.closePipe = false;
   this.statusStr = "";
   this.outQueue = "";
@@ -136,50 +175,57 @@ function MimeDecryptHandler() {
   this.mimePartNumber = "";
   this.dataIsBase64 = null;
   this.base64Cache = "";
 
   this.onDataAvailable = this.onDataAvailable68;
 }
 
 MimeDecryptHandler.prototype = {
-  inStream: Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream),
+  inStream: Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+    Ci.nsIScriptableInputStream
+  ),
 
-  onStartRequest: function(request, uri) {
-    if (!EnigmailCore.getService()) // Ensure Enigmail is initialized
+  onStartRequest(request, uri) {
+    if (!EnigmailCore.getService()) {
+      // Ensure Enigmail is initialized
       return;
+    }
     EnigmailLog.DEBUG("mimeDecrypt.jsm: onStartRequest\n"); // always log this one
 
     ++gNumProc;
     if (gNumProc > EnigmailPrefs.getPref("maxNumProcesses")) {
-      EnigmailLog.DEBUG("mimeDecrypt.jsm: number of parallel requests above threshold - ignoring requst\n");
+      EnigmailLog.DEBUG(
+        "mimeDecrypt.jsm: number of parallel requests above threshold - ignoring requst\n"
+      );
       return;
     }
 
     this.initOk = true;
     this.mimeSvc = request.QueryInterface(Ci.nsIPgpMimeProxy);
     if ("mimePart" in this.mimeSvc) {
       this.mimePartNumber = this.mimeSvc.mimePart;
     } else {
       this.mimePartNumber = "";
     }
 
     if ("messageURI" in this.mimeSvc) {
       this.uri = this.mimeSvc.messageURI;
       if (this.uri) {
-        EnigmailLog.DEBUG("mimeDecrypt.jsm: onStartRequest: uri='" + this.uri.spec + "'\n");
-      }
-      else {
+        EnigmailLog.DEBUG(
+          "mimeDecrypt.jsm: onStartRequest: uri='" + this.uri.spec + "'\n"
+        );
+      } else {
         EnigmailLog.DEBUG("mimeDecrypt.jsm: onStartRequest: uri=null\n");
       }
-    } else {
-      if (uri) {
-        this.uri = uri.QueryInterface(Ci.nsIURI);
-        EnigmailLog.DEBUG("mimeDecrypt.jsm: onStartRequest: uri='" + this.uri.spec + "'\n");
-      }
+    } else if (uri) {
+      this.uri = uri.QueryInterface(Ci.nsIURI);
+      EnigmailLog.DEBUG(
+        "mimeDecrypt.jsm: onStartRequest: uri='" + this.uri.spec + "'\n"
+      );
     }
     this.pipe = null;
     this.closePipe = false;
     this.exitCode = null;
     this.msgWindow = EnigmailVerify.lastMsgWindow;
     this.msgUriSpec = EnigmailVerify.lastMsgUri;
 
     this.statusDisplayed = false;
@@ -198,65 +244,62 @@ MimeDecryptHandler.prototype = {
     this.xferEncoding = ENCODING_DEFAULT;
     this.boundary = EnigmailMime.getBoundary(this.mimeSvc.contentType);
 
     if (!this.isReloadingLastMessage()) {
       EnigmailSingletons.clearLastDecryptedMessage();
     }
   },
 
-  processData: function(data) {
+  processData(data) {
     // detect MIME part boundary
-    if (data.indexOf(this.boundary) >= 0) {
+    if (data.includes(this.boundary)) {
       LOCAL_DEBUG("mimeDecrypt.jsm: processData: found boundary\n");
       ++this.mimePartCount;
       this.headerMode = 1;
       return;
     }
 
     // found PGP/MIME "body"
     if (this.mimePartCount == 2) {
-
       if (this.headerMode == 1) {
         // we are in PGP/MIME main part headers
         if (data.search(/\r|\n/) === 0) {
           // end of Mime-part headers reached
           this.headerMode = 2;
-          return;
-        } else {
-          if (data.search(/^content-transfer-encoding:\s*/i) >= 0) {
-            // extract content-transfer-encoding
-            data = data.replace(/^content-transfer-encoding:\s*/i, "");
-            data = data.replace(/;.*/, "").toLowerCase().trim();
-            if (data.search(/base64/i) >= 0) {
-              this.xferEncoding = ENCODING_BASE64;
-            } else if (data.search(/quoted-printable/i) >= 0) {
-              this.xferEncoding = ENCODING_QP;
-            }
-
+        } else if (data.search(/^content-transfer-encoding:\s*/i) >= 0) {
+          // extract content-transfer-encoding
+          data = data.replace(/^content-transfer-encoding:\s*/i, "");
+          data = data
+            .replace(/;.*/, "")
+            .toLowerCase()
+            .trim();
+          if (data.search(/base64/i) >= 0) {
+            this.xferEncoding = ENCODING_BASE64;
+          } else if (data.search(/quoted-printable/i) >= 0) {
+            this.xferEncoding = ENCODING_QP;
           }
         }
+        // else: PGP/MIME main part body
+      } else if (this.xferEncoding == ENCODING_QP) {
+        this.cacheData(EnigmailData.decodeQuotedPrintable(data));
       } else {
-        // PGP/MIME main part body
-        if (this.xferEncoding == ENCODING_QP) {
-          this.cacheData(EnigmailData.decodeQuotedPrintable(data));
-        } else {
-          this.cacheData(data);
-        }
+        this.cacheData(data);
       }
     }
   },
 
   /**
    * onDataAvailable for TB >= 68
    */
-  onDataAvailable68: function(req, stream, offset, count) {
-
+  onDataAvailable68(req, stream, offset, count) {
     // get data from libmime
-    if (!this.initOk) return;
+    if (!this.initOk) {
+      return;
+    }
     this.inStream.init(stream);
 
     if (count > 0) {
       var data = this.inStream.read(count);
 
       if (this.mimePartCount == 0 && this.dataIsBase64 === null) {
         // try to determine if this could be a base64 encoded message part
         this.dataIsBase64 = this.isBase64Encoding(data);
@@ -265,56 +308,58 @@ MimeDecryptHandler.prototype = {
       if (!this.dataIsBase64) {
         if (data.search(/[\r\n][^\r\n]+[\r\n]/) >= 0) {
           // process multi-line data line by line
           let lines = data.replace(/\r\n/g, "\n").split(/\n/);
 
           for (let i = 0; i < lines.length; i++) {
             this.processData(lines[i] + "\r\n");
           }
-        } else
+        } else {
           this.processData(data);
+        }
       } else {
         this.base64Cache += data;
       }
     }
   },
 
   /**
    * Try to determine if data is base64 endoded
    */
-  isBase64Encoding: function(str) {
+  isBase64Encoding(str) {
     let ret = false;
 
     str = str.replace(/[\r\n]/, "");
     if (str.search(/^[A-Za-z0-9+/=]+$/) === 0) {
       let excess = str.length % 4;
       str = str.substring(0, str.length - excess);
 
       try {
-        let s = atob(str);
+        atob(str);
         // if the conversion succeds, we have a base64 encoded message
         ret = true;
       } catch (ex) {
         // not a base64 encoded
       }
     }
 
     return ret;
   },
 
   // cache encrypted data
-  cacheData: function(str) {
-    if (gDebugLogLevel > 4)
+  cacheData(str) {
+    if (gDebugLogLevel > 4) {
       LOCAL_DEBUG("mimeDecrypt.jsm: cacheData: " + str.length + "\n");
+    }
 
     this.outQueue += str;
   },
 
-  processBase64Message: function() {
+  processBase64Message() {
     LOCAL_DEBUG("mimeDecrypt.jsm: processBase64Message\n");
 
     try {
       this.base64Cache = EnigmailData.decodeBase64(this.base64Cache);
     } catch (ex) {
       // if decoding failed, try non-encoded version
     }
 
@@ -325,41 +370,56 @@ MimeDecryptHandler.prototype = {
     }
   },
 
   /**
    * Determine if we are reloading the same message as the previous one
    *
    * @return Boolean
    */
-  isReloadingLastMessage: function() {
-    if (!this.uri) return false;
-    if (!LAST_MSG.lastMessageURI) return false;
-    if (("lastMessageData" in LAST_MSG) && LAST_MSG.lastMessageData === "") return false;
-    if (this.isUrlEnigmailConvert()) return false;
+  isReloadingLastMessage() {
+    if (!this.uri) {
+      return false;
+    }
+    if (!LAST_MSG.lastMessageURI) {
+      return false;
+    }
+    if ("lastMessageData" in LAST_MSG && LAST_MSG.lastMessageData === "") {
+      return false;
+    }
+    if (this.isUrlEnigmailConvert()) {
+      return false;
+    }
 
     let currMsg = EnigmailURIs.msgIdentificationFromUrl(this.uri);
 
-    if (LAST_MSG.lastMessageURI.folder === currMsg.folder && LAST_MSG.lastMessageURI.msgNum === currMsg.msgNum) {
+    if (
+      LAST_MSG.lastMessageURI.folder === currMsg.folder &&
+      LAST_MSG.lastMessageURI.msgNum === currMsg.msgNum
+    ) {
       return true;
     }
 
     return false;
   },
 
-  isUrlEnigmailConvert: function() {
-    if (!this.uri) return false;
+  isUrlEnigmailConvert() {
+    if (!this.uri) {
+      return false;
+    }
 
-    return (this.uri.spec.search(/[&?]header=enigmailConvert/) >= 0);
+    return this.uri.spec.search(/[&?]header=enigmailConvert/) >= 0;
   },
 
-  onStopRequest: function(request, status, dummy) {
+  onStopRequest(request, status, dummy) {
     LOCAL_DEBUG("mimeDecrypt.jsm: onStopRequest\n");
     --gNumProc;
-    if (!this.initOk) return;
+    if (!this.initOk) {
+      return;
+    }
 
     if (this.dataIsBase64) {
       this.processBase64Message();
     }
 
     this.msgWindow = EnigmailVerify.lastMsgWindow;
     this.msgUriSpec = EnigmailVerify.lastMsgUri;
 
@@ -367,157 +427,188 @@ MimeDecryptHandler.prototype = {
     let currMsg = EnigmailURIs.msgIdentificationFromUrl(this.uri);
 
     this.backgroundJob = false;
 
     if (this.uri) {
       // return if not decrypting currently displayed message (except if
       // printing, replying, etc)
 
-      this.backgroundJob = (this.uri.spec.search(/[&?]header=(print|quotebody|enigmailConvert)/) >= 0);
+      this.backgroundJob =
+        this.uri.spec.search(/[&?]header=(print|quotebody|enigmailConvert)/) >=
+        0;
 
       try {
-        var messenger = Cc["@mozilla.org/messenger;1"].getService(Ci.nsIMessenger);
-
         if (!EnigmailPrefs.getPref("autoDecrypt")) {
           // "decrypt manually" mode
           let manUrl = {};
 
           if (EnigmailVerify.getManualUri()) {
-            manUrl.value = EnigmailCompat.getUrlFromUriSpec(EnigmailVerify.getManualUri());
+            manUrl.value = EnigmailCompat.getUrlFromUriSpec(
+              EnigmailVerify.getManualUri()
+            );
           } else {
             manUrl.value = {
-              spec: "enigmail://invalid/message"
+              spec: "enigmail://invalid/message",
             };
           }
 
           // print a message if not message explicitly decrypted
-          let currUrlSpec = this.uri.spec.replace(/(\?.*)(number=[0-9]*)(&.*)?$/, "?$2");
-          let manUrlSpec = manUrl.value.spec.replace(/(\?.*)(number=[0-9]*)(&.*)?$/, "?$2");
+          let currUrlSpec = this.uri.spec.replace(
+            /(\?.*)(number=[0-9]*)(&.*)?$/,
+            "?$2"
+          );
+          let manUrlSpec = manUrl.value.spec.replace(
+            /(\?.*)(number=[0-9]*)(&.*)?$/,
+            "?$2"
+          );
 
-
-          if ((!this.backgroundJob) && currUrlSpec.indexOf(manUrlSpec) !== 0) {
+          if (!this.backgroundJob && currUrlSpec.indexOf(manUrlSpec) !== 0) {
             this.handleManualDecrypt();
             return;
           }
         }
 
         if (this.msgUriSpec) {
           url.value = EnigmailCompat.getUrlFromUriSpec(this.msgUriSpec);
         }
 
-        if (this.uri.spec.search(/[&?]header=[^&]+/) > 0 &&
-          this.uri.spec.search(/[&?]examineEncryptedParts=true/) < 0) {
-
-          if (this.uri.spec.search(/[&?]header=(filter|enigmailFilter)(&.*)?$/) > 0) {
-            EnigmailLog.DEBUG("mimeDecrypt.jsm: onStopRequest: detected incoming message processing\n");
+        if (
+          this.uri.spec.search(/[&?]header=[^&]+/) > 0 &&
+          this.uri.spec.search(/[&?]examineEncryptedParts=true/) < 0
+        ) {
+          if (
+            this.uri.spec.search(/[&?]header=(filter|enigmailFilter)(&.*)?$/) >
+            0
+          ) {
+            EnigmailLog.DEBUG(
+              "mimeDecrypt.jsm: onStopRequest: detected incoming message processing\n"
+            );
             return;
           }
         }
 
-        if (this.uri.spec.search(/[&?]header=[^&]+/) < 0 &&
+        if (
+          this.uri.spec.search(/[&?]header=[^&]+/) < 0 &&
           this.uri.spec.search(/[&?]part=[.0-9]+/) < 0 &&
-          this.uri.spec.search(/[&?]examineEncryptedParts=true/) < 0) {
-
+          this.uri.spec.search(/[&?]examineEncryptedParts=true/) < 0
+        ) {
           if (this.uri && url && url.value) {
-
-            if ("path" in url) {
-              // TB < 57
-              if (url.value.host !== this.uri.host ||
-                url.value.path !== this.uri.path)
-                return;
-            } else {
-              // TB >= 57
-              if (url.value.host !== this.uri.host ||
-                url.value.pathQueryRef !== this.uri.pathQueryRef)
-                return;
+            if (
+              url.value.host !== this.uri.host ||
+              url.value.pathQueryRef !== this.uri.pathQueryRef
+            ) {
+              return;
             }
           }
         }
       } catch (ex) {
         EnigmailLog.writeException("mimeDecrypt.js", ex);
-        EnigmailLog.DEBUG("mimeDecrypt.jsm: error while processing " + this.msgUriSpec + "\n");
+        EnigmailLog.DEBUG(
+          "mimeDecrypt.jsm: error while processing " + this.msgUriSpec + "\n"
+        );
       }
     }
 
     let spec = this.uri ? this.uri.spec : null;
-    EnigmailLog.DEBUG(`mimeDecrypt.jsm: checking MIME structure for ${this.mimePartNumber} / ${spec}\n`);
+    EnigmailLog.DEBUG(
+      `mimeDecrypt.jsm: checking MIME structure for ${
+        this.mimePartNumber
+      } / ${spec}\n`
+    );
 
-    if (!EnigmailMime.isRegularMimeStructure(this.mimePartNumber, spec, false)) {
+    if (
+      !EnigmailMime.isRegularMimeStructure(this.mimePartNumber, spec, false)
+    ) {
       if (!this.isUrlEnigmailConvert()) {
         this.returnData(EnigmailMimeDecrypt.emptyAttachment());
       } else {
-        throw new Error("Cannot decrypt messages with mixed (encrypted/non-encrypted) content");
+        throw new Error(
+          "Cannot decrypt messages with mixed (encrypted/non-encrypted) content"
+        );
       }
       return;
     }
 
     if (!this.isReloadingLastMessage()) {
       if (this.xferEncoding == ENCODING_BASE64) {
         this.outQueue = EnigmailData.decodeBase64(this.outQueue) + "\n";
       }
 
       let win = this.msgWindow;
 
-      if (!EnigmailDecryption.isReady(win)) return;
+      if (!EnigmailDecryption.isReady(win)) {
+        return;
+      }
 
       // limit output to 100 times message size to avoid DoS attack
       let maxOutput = this.outQueue.length * 100;
-      let statusFlagsObj = {};
-      let errorMsgObj = {};
-      let listener = this;
 
       EnigmailLog.DEBUG("mimeDecryp.jsm: starting decryption\n");
       EnigmailLog.DEBUG(this.outQueue + "\n");
 
       let keyserver = EnigmailPrefs.getPref("autoKeyRetrieve");
       let options = {
-        keyserver: keyserver,
+        keyserver,
         keyserverProxy: EnigmailHttpProxy.getHttpProxy(keyserver),
         fromAddr: EnigmailDecryption.getFromAddr(win),
-        maxOutputLength: maxOutput
+        maxOutputLength: maxOutput,
       };
       const cApi = EnigmailCryptoAPI();
       EnigmailLog.DEBUG("mimeDecrypt.jsm: got API: " + cApi.api_name + "\n");
       this.returnStatus = cApi.sync(cApi.decryptMime(this.outQueue, options));
       if (!this.returnStatus) {
         this.returnStatus = {
           decryptedData: "",
           exitCode: -1,
-          statusFlags: EnigmailConstants.DECRYPTION_FAILED
+          statusFlags: EnigmailConstants.DECRYPTION_FAILED,
         };
       }
       this.decryptedData = this.returnStatus.decryptedData;
       this.handleResult(this.returnStatus.exitCode);
 
-      let mdcError = ((this.returnStatus.statusFlags & EnigmailConstants.DECRYPTION_FAILED) ||
-        !(this.returnStatus.statusFlags & EnigmailConstants.DECRYPTION_OKAY));
+      let mdcError =
+        this.returnStatus.statusFlags & EnigmailConstants.DECRYPTION_FAILED ||
+        !(this.returnStatus.statusFlags & EnigmailConstants.DECRYPTION_OKAY);
 
       if (!this.isUrlEnigmailConvert()) {
         // don't return decrypted data if decryption failed (because it's likely an MDC error),
         // unless we are called for permanent decryption
         if (mdcError) {
           this.decryptedData = "";
         }
       }
 
       this.displayStatus();
 
       // HACK: remove filename from 1st HTML and plaintext parts to make TB display message without attachment
-      this.decryptedData = this.decryptedData.replace(/^Content-Disposition: inline; filename="msg.txt"/m, "Content-Disposition: inline");
-      this.decryptedData = this.decryptedData.replace(/^Content-Disposition: inline; filename="msg.html"/m, "Content-Disposition: inline");
+      this.decryptedData = this.decryptedData.replace(
+        /^Content-Disposition: inline; filename="msg.txt"/m,
+        "Content-Disposition: inline"
+      );
+      this.decryptedData = this.decryptedData.replace(
+        /^Content-Disposition: inline; filename="msg.html"/m,
+        "Content-Disposition: inline"
+      );
 
-      let prefix = EnigmailMimeDecrypt.pretendAttachment(this.mimePartNumber, this.uri);
+      let prefix = EnigmailMimeDecrypt.pretendAttachment(
+        this.mimePartNumber,
+        this.uri
+      );
       this.returnData(prefix + this.decryptedData);
 
       // don't remember the last message if it contains an embedded PGP/MIME message
       // to avoid ending up in a loop
-      if (this.mimePartNumber === "1" &&
-        this.decryptedData.search(/^Content-Type:[\t ]+multipart\/encrypted/mi) < 0 &&
-        !mdcError) {
+      if (
+        this.mimePartNumber === "1" &&
+        this.decryptedData.search(
+          /^Content-Type:[\t ]+multipart\/encrypted/im
+        ) < 0 &&
+        !mdcError
+      ) {
         LAST_MSG.lastMessageData = this.decryptedData;
         LAST_MSG.lastMessageURI = currMsg;
         LAST_MSG.lastStatus = this.returnStatus;
         LAST_MSG.lastStatus.decryptedHeaders = this.decryptedHeaders;
         LAST_MSG.lastStatus.mimePartNumber = this.mimePartNumber;
       } else {
         LAST_MSG.lastMessageURI = null;
         LAST_MSG.lastMessageData = "";
@@ -531,233 +622,290 @@ MimeDecryptHandler.prototype = {
       this.decryptedHeaders = LAST_MSG.lastStatus.decryptedHeaders;
       this.mimePartNumber = LAST_MSG.lastStatus.mimePartNumber;
       this.exitCode = 0;
       this.displayStatus();
       this.returnData(LAST_MSG.lastMessageData);
     }
   },
 
-  displayStatus: function() {
+  displayStatus() {
     EnigmailLog.DEBUG("mimeDecrypt.jsm: displayStatus()\n");
 
-    if (this.exitCode === null || this.msgWindow === null || this.statusDisplayed) {
+    if (
+      this.exitCode === null ||
+      this.msgWindow === null ||
+      this.statusDisplayed
+    ) {
       EnigmailLog.DEBUG("mimeDecrypt.jsm: displayStatus: nothing to display\n");
       return;
     }
 
-    let uriSpec = (this.uri ? this.uri.spec : null);
+    let uriSpec = this.uri ? this.uri.spec : null;
 
     try {
-      EnigmailLog.DEBUG("mimeDecrypt.jsm: displayStatus for uri " + uriSpec + "\n");
+      EnigmailLog.DEBUG(
+        "mimeDecrypt.jsm: displayStatus for uri " + uriSpec + "\n"
+      );
       let headerSink = EnigmailSingletons.messageReader;
 
       if (headerSink && this.uri && !this.backgroundJob) {
-
-        headerSink.processDecryptionResult(this.uri, "modifyMessageHeaders", JSON.stringify(this.decryptedHeaders), this.mimePartNumber);
+        headerSink.processDecryptionResult(
+          this.uri,
+          "modifyMessageHeaders",
+          JSON.stringify(this.decryptedHeaders),
+          this.mimePartNumber
+        );
 
         headerSink.updateSecurityStatus(
           this.msgUriSpec,
           this.exitCode,
           this.returnStatus.statusFlags,
           this.returnStatus.keyId,
           this.returnStatus.userId,
           this.returnStatus.sigDetails,
           this.returnStatus.errorMsg,
           this.returnStatus.blockSeparation,
           this.uri,
           JSON.stringify({
-            encryptedTo: this.returnStatus.encToDetails
+            encryptedTo: this.returnStatus.encToDetails,
           }),
-          this.mimePartNumber);
+          this.mimePartNumber
+        );
       } else {
         this.updateHeadersInMsgDb();
       }
       this.statusDisplayed = true;
     } catch (ex) {
       EnigmailLog.writeException("mimeDecrypt.jsm", ex);
     }
     LOCAL_DEBUG("mimeDecrypt.jsm: displayStatus done\n");
   },
 
-  handleResult: function(exitCode) {
+  handleResult(exitCode) {
     LOCAL_DEBUG("mimeDecrypt.jsm: done: " + exitCode + "\n");
 
-    if (gDebugLogLevel > 4)
-      LOCAL_DEBUG("mimeDecrypt.jsm: done: decrypted data='" + this.decryptedData + "'\n");
+    if (gDebugLogLevel > 4) {
+      LOCAL_DEBUG(
+        "mimeDecrypt.jsm: done: decrypted data='" + this.decryptedData + "'\n"
+      );
+    }
 
     // ensure newline at the end of the stream
     if (!this.decryptedData.endsWith("\n")) {
       this.decryptedData += "\r\n";
     }
 
     try {
       this.extractEncryptedHeaders();
       this.extractAutocryptGossip();
     } catch (ex) {}
 
     let i = this.decryptedData.search(/\n\r?\n/);
     if (i > 0) {
       var hdr = this.decryptedData.substr(0, i).split(/\r?\n/);
       for (let j = 0; j < hdr.length; j++) {
         if (hdr[j].search(/^\s*content-type:\s+text\/(plain|html)/i) >= 0) {
-          LOCAL_DEBUG("mimeDecrypt.jsm: done: adding multipart/mixed around " + hdr[j] + "\n");
+          LOCAL_DEBUG(
+            "mimeDecrypt.jsm: done: adding multipart/mixed around " +
+              hdr[j] +
+              "\n"
+          );
 
           this.addWrapperToDecryptedResult();
           break;
         }
       }
     }
 
     this.exitCode = exitCode;
   },
 
-  addWrapperToDecryptedResult: function() {
+  addWrapperToDecryptedResult() {
     if (!this.isUrlEnigmailConvert()) {
       let wrapper = EnigmailMime.createBoundary();
 
-      this.decryptedData = 'Content-Type: multipart/mixed; boundary="' + wrapper + '"\r\n' +
-        'Content-Disposition: inline\r\n\r\n' +
-        '--' + wrapper + '\r\n' +
-        this.decryptedData + '\r\n' +
-        '--' + wrapper + '--\r\n';
+      this.decryptedData =
+        'Content-Type: multipart/mixed; boundary="' +
+        wrapper +
+        '"\r\n' +
+        "Content-Disposition: inline\r\n\r\n" +
+        "--" +
+        wrapper +
+        "\r\n" +
+        this.decryptedData +
+        "\r\n" +
+        "--" +
+        wrapper +
+        "--\r\n";
     }
   },
 
-  extractContentType: function(data) {
+  extractContentType(data) {
     let i = data.search(/\n\r?\n/);
-    if (i <= 0) return null;
+    if (i <= 0) {
+      return null;
+    }
 
-    let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     headers.initialize(data.substr(0, i));
     return headers.extractHeader("content-type", false);
   },
 
   // return data to libMime
-  returnData: function(data) {
-    EnigmailLog.DEBUG("mimeDecrypt.jsm: returnData: " + data.length + " bytes\n");
+  returnData(data) {
+    EnigmailLog.DEBUG(
+      "mimeDecrypt.jsm: returnData: " + data.length + " bytes\n"
+    );
 
     let proto = null;
     let ct = this.extractContentType(data);
     if (ct && ct.search(/multipart\/signed/i) >= 0) {
       proto = EnigmailMime.getProtocol(ct);
     }
 
     try {
-      if (proto && proto.search(/application\/(pgp|pkcs7|x-pkcs7)-signature/i) >= 0) {
-        EnigmailLog.DEBUG("mimeDecrypt.jsm: returnData: using direct verification\n");
+      if (
+        proto &&
+        proto.search(/application\/(pgp|pkcs7|x-pkcs7)-signature/i) >= 0
+      ) {
+        EnigmailLog.DEBUG(
+          "mimeDecrypt.jsm: returnData: using direct verification\n"
+        );
         this.mimeSvc.contentType = ct;
         if ("mimePart" in this.mimeSvc) {
           this.mimeSvc.mimePart = this.mimeSvc.mimePart + ".1";
         }
         let veri = EnigmailVerify.newVerifier(proto);
         veri.onStartRequest(this.mimeSvc, this.uri);
         veri.onTextData(data);
         veri.onStopRequest(null, 0);
+      } else if ("outputDecryptedData" in this.mimeSvc) {
+        // TB >= 57
+        this.mimeSvc.outputDecryptedData(data, data.length);
       } else {
-        if ("outputDecryptedData" in this.mimeSvc) {
-          // TB >= 57
-          this.mimeSvc.outputDecryptedData(data, data.length);
-        } else {
-          let gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
-          gConv.setData(data, data.length);
-          this.mimeSvc.onStartRequest(null, null);
-          this.mimeSvc.onDataAvailable(null, null, gConv, 0, data.length);
-          this.mimeSvc.onStopRequest(null, null, 0);
-        }
+        let gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
+          Ci.nsIStringInputStream
+        );
+        gConv.setData(data, data.length);
+        this.mimeSvc.onStartRequest(null, null);
+        this.mimeSvc.onDataAvailable(null, null, gConv, 0, data.length);
+        this.mimeSvc.onStopRequest(null, null, 0);
       }
     } catch (ex) {
-      EnigmailLog.ERROR("mimeDecrypt.jsm: returnData(): mimeSvc.onDataAvailable failed:\n" + ex.toString());
+      EnigmailLog.ERROR(
+        "mimeDecrypt.jsm: returnData(): mimeSvc.onDataAvailable failed:\n" +
+          ex.toString()
+      );
     }
   },
 
-  handleManualDecrypt: function() {
-
+  handleManualDecrypt() {
     try {
       let headerSink = EnigmailSingletons.messageReader;
 
       if (headerSink && this.uri && !this.backgroundJob) {
         headerSink.updateSecurityStatus(
           this.msgUriSpec,
           EnigmailConstants.POSSIBLE_PGPMIME,
           0,
           "",
           "",
           "",
           EnigmailLocale.getString("possiblyPgpMime"),
           "",
           this.uri,
           null,
-          "");
+          ""
+        );
       }
     } catch (ex) {}
 
     return 0;
   },
 
-  updateHeadersInMsgDb: function() {
-    if (this.mimePartNumber !== "1") return;
-    if (!this.uri) return;
+  updateHeadersInMsgDb() {
+    if (this.mimePartNumber !== "1") {
+      return;
+    }
+    if (!this.uri) {
+      return;
+    }
 
-    if (this.decryptedHeaders && ("subject" in this.decryptedHeaders)) {
+    if (this.decryptedHeaders && "subject" in this.decryptedHeaders) {
       try {
-        let msgDbHdr = this.uri.QueryInterface(Ci.nsIMsgMessageUrl).messageHeader;
-        msgDbHdr.subject = EnigmailData.convertFromUnicode(this.decryptedHeaders.subject, "utf-8");
+        let msgDbHdr = this.uri.QueryInterface(Ci.nsIMsgMessageUrl)
+          .messageHeader;
+        msgDbHdr.subject = EnigmailData.convertFromUnicode(
+          this.decryptedHeaders.subject,
+          "utf-8"
+        );
       } catch (x) {}
     }
   },
 
-  extractEncryptedHeaders: function() {
+  extractEncryptedHeaders() {
     let r = EnigmailMime.extractProtectedHeaders(this.decryptedData);
-    if (!r) return;
+    if (!r) {
+      return;
+    }
 
     this.decryptedHeaders = r.newHeaders;
     if (r.startPos >= 0 && r.endPos > r.startPos) {
-      this.decryptedData = this.decryptedData.substr(0, r.startPos) + this.decryptedData.substr(r.endPos);
+      this.decryptedData =
+        this.decryptedData.substr(0, r.startPos) +
+        this.decryptedData.substr(r.endPos);
     }
   },
 
-  extractAutocryptGossip: async function() {
+  async extractAutocryptGossip() {
     let m1 = this.decryptedData.search(/^--/m);
     let m2 = this.decryptedData.search(/\r?\n\r?\n/);
     let m = Math.max(m1, m2);
 
-    let hdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let hdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     hdr.initialize(this.decryptedData.substr(0, m));
 
     let gossip = hdr.getHeader("autocrypt-gossip") || [];
-    EnigmailLog.DEBUG(`mimeDecrypt.jsm: extractAutocryptGossip: found ${gossip.length} headers\n`);
+    EnigmailLog.DEBUG(
+      `mimeDecrypt.jsm: extractAutocryptGossip: found ${
+        gossip.length
+      } headers\n`
+    );
 
     let msgDate = null;
     try {
-      msgDate = this.uri.QueryInterface(Ci.nsIMsgMessageUrl).messageHeader.dateInSeconds;
+      msgDate = this.uri.QueryInterface(Ci.nsIMsgMessageUrl).messageHeader
+        .dateInSeconds;
     } catch (x) {}
 
-
     for (let i in gossip) {
       let addr = EnigmailMime.getParameter(gossip[i], "addr");
       try {
-        let r = await EnigmailAutocrypt.processAutocryptHeader(addr, [gossip[i].replace(/ /g, "")], msgDate, true, true);
+        let r = await EnigmailAutocrypt.processAutocryptHeader(
+          addr,
+          [gossip[i].replace(/ /g, "")],
+          msgDate,
+          true,
+          true
+        );
         EnigmailLog.DEBUG(`mimeDecrypt.jsm: extractAutocryptGossip: r=${r}\n`);
       } catch (x) {
-        EnigmailLog.DEBUG(`mimeDecrypt.jsm: extractAutocryptGossip: Error: ${x}\n`);
+        EnigmailLog.DEBUG(
+          `mimeDecrypt.jsm: extractAutocryptGossip: Error: ${x}\n`
+        );
       }
     }
-  }
+  },
 };
 
-
 ////////////////////////////////////////////////////////////////////
 // General-purpose functions, not exported
 
 function LOCAL_DEBUG(str) {
-  if (gDebugLogLevel) EnigmailLog.DEBUG(str);
-}
-
-function initModule() {
-  var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
-  var nspr_log_modules = env.get("NSPR_LOG_MODULES");
-  var matches = nspr_log_modules.match(/mimeDecrypt:(\d+)/);
-
-  if (matches && (matches.length > 1)) {
-    gDebugLogLevel = matches[1];
+  if (gDebugLogLevel) {
+    EnigmailLog.DEBUG(str);
   }
 }
--- a/mail/extensions/openpgp/content/modules/mimeEncrypt.jsm
+++ b/mail/extensions/openpgp/content/modules/mimeEncrypt.jsm
@@ -6,41 +6,57 @@
 
 /**
  *  Module for creating PGP/MIME signed and/or encrypted messages
  *  implemented as XPCOM component
  */
 
 var EXPORTED_SYMBOLS = ["EnigmailMimeEncrypt"];
 
-const Cr = Components.results;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailEncryption = ChromeUtils.import("chrome://openpgp/content/modules/encryption.jsm").EnigmailEncryption;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailHash = ChromeUtils.import("chrome://openpgp/content/modules/hash.jsm").EnigmailHash;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailEncryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/encryption.jsm"
+).EnigmailEncryption;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailHash = ChromeUtils.import(
+  "chrome://openpgp/content/modules/hash.jsm"
+).EnigmailHash;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
 
 // our own contract IDs
-const PGPMIME_ENCRYPT_CID = Components.ID("{96fe88f9-d2cd-466f-93e0-3a351df4c6d2}");
+const PGPMIME_ENCRYPT_CID = Components.ID(
+  "{96fe88f9-d2cd-466f-93e0-3a351df4c6d2}"
+);
 const PGPMIME_ENCRYPT_CONTRACTID = "@enigmail.net/compose/mimeencrypt;1";
 
-const APPSHELL_MEDIATOR_CONTRACTID = "@mozilla.org/appshell/window-mediator;1";
-
-// S/MIME contract IDs
-const SMIME_ENCRYPT_CONTRACTID = "@mozilla.org/messengercompose/composesecure;1";
-const kSmimeComposeSecureCID = "{dd753201-9a23-4e08-957f-b3616bf7e012}";
-
 const maxBufferLen = 102400;
 const MIME_SIGNED = 1;
 const MIME_ENCRYPTED = 2;
 
 var gDebugLogLevel = 0;
 
 function PgpMimeEncrypt(sMimeSecurityInfo) {
   this.wrappedJSObject = this;
@@ -60,23 +76,24 @@ function PgpMimeEncrypt(sMimeSecurityInf
   this.originalSubject = null;
   this.keyMap = {};
 
   this.onDataAvailable = this.onDataAvailable68;
 
   try {
     if (sMimeSecurityInfo) {
       if ("nsIMsgSMIMECompFields" in Ci) {
-        sMimeSecurityInfo = sMimeSecurityInfo.QueryInterface(Ci.nsIMsgSMIMECompFields);
+        sMimeSecurityInfo = sMimeSecurityInfo.QueryInterface(
+          Ci.nsIMsgSMIMECompFields
+        );
       }
       this.signMessage = sMimeSecurityInfo.signMessage;
       this.requireEncryptMessage = sMimeSecurityInfo.requireEncryptMessage;
     }
-  }
-  catch (ex) {}
+  } catch (ex) {}
 }
 
 PgpMimeEncrypt.prototype = {
   classDescription: "Enigmail JS Encryption Handler",
   classID: PGPMIME_ENCRYPT_CID,
   get contractID() {
     return PGPMIME_ENCRYPT_CONTRACTID;
   },
@@ -85,17 +102,19 @@ PgpMimeEncrypt.prototype = {
     "nsIStreamListener",
   ]),
 
   signMessage: false,
   requireEncryptMessage: false,
 
   // private variables
 
-  inStream: Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream),
+  inStream: Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+    Ci.nsIScriptableInputStream
+  ),
   msgCompFields: null,
   smimeCompose: null,
   useSmime: false,
   outStringStream: null,
 
   // 0: processing headers
   // 1: processing body
   // 2: skipping header
@@ -115,319 +134,384 @@ PgpMimeEncrypt.prototype = {
   outQueue: "",
   closePipe: false,
   cryptoMode: 0,
   exitCode: -1,
   inspector: null,
   checkSMime: true,
 
   // nsIStreamListener interface
-  onStartRequest: function(request) {
+  onStartRequest(request) {
     EnigmailLog.DEBUG("mimeEncrypt.js: onStartRequest\n");
     this.encHeader = null;
   },
 
-  /**
-   * onDataAvailable for TB <= 66
-   */
-  onDataAvailable60: function(req, ctxt, stream, offset, count) {
+  onDataAvailable68(req, stream, offset, count) {
     LOCAL_DEBUG("mimeEncrypt.js: onDataAvailable\n");
     this.inStream.init(stream);
-    var data = this.inStream.read(count);
+    //var data = this.inStream.read(count);
     //LOCAL_DEBUG("mimeEncrypt.js: >"+data+"<\n");
-
   },
 
-  /**
-   * onDataAvailable for TB >= 67
-   */
-  onDataAvailable68: function(req, stream, offset, count) {
-    LOCAL_DEBUG("mimeEncrypt.js: onDataAvailable\n");
-    this.inStream.init(stream);
-    var data = this.inStream.read(count);
-    //LOCAL_DEBUG("mimeEncrypt.js: >"+data+"<\n");
-
-  },
-
-  onStopRequest: function(request, status) {
+  onStopRequest(request, status) {
     EnigmailLog.DEBUG("mimeEncrypt.js: onStopRequest\n");
   },
 
-  disableSMimeCheck: function() {
+  disableSMimeCheck() {
     this.useSmime = false;
     this.checkSMime = false;
   },
 
   // nsIMsgComposeSecure interface
-  requiresCryptoEncapsulation: function(msgIdentity, msgCompFields) {
+  requiresCryptoEncapsulation(msgIdentity, msgCompFields) {
     EnigmailLog.DEBUG("mimeEncrypt.js: requiresCryptoEncapsulation\n");
     try {
-        // TB >= 64: we are not called for S/MIME
-        this.disableSMimeCheck();
+      // TB >= 64: we are not called for S/MIME
+      this.disableSMimeCheck();
 
-        return (this.sendFlags & (EnigmailConstants.SEND_SIGNED |
-          EnigmailConstants.SEND_ENCRYPTED |
-          EnigmailConstants.SEND_VERBATIM)) !== 0;
-    }
-    catch (ex) {
+      return (
+        (this.sendFlags &
+          (EnigmailConstants.SEND_SIGNED |
+            EnigmailConstants.SEND_ENCRYPTED |
+            EnigmailConstants.SEND_VERBATIM)) !==
+        0
+      );
+    } catch (ex) {
       EnigmailLog.writeException("mimeEncrypt.js", ex);
-      throw (ex);
+      throw ex;
     }
   },
 
-  beginCryptoEncapsulation: function(outStream, recipientList, msgCompFields, msgIdentity, sendReport, isDraft) {
+  beginCryptoEncapsulation(
+    outStream,
+    recipientList,
+    msgCompFields,
+    msgIdentity,
+    sendReport,
+    isDraft
+  ) {
     EnigmailLog.DEBUG("mimeEncrypt.js: beginCryptoEncapsulation\n");
 
-    if (this.checkSMime && (!this.smimeCompose)) {
-      LOCAL_DEBUG("mimeEncrypt.js: beginCryptoEncapsulation: ERROR MsgComposeSecure not instantiated\n");
+    if (this.checkSMime && !this.smimeCompose) {
+      LOCAL_DEBUG(
+        "mimeEncrypt.js: beginCryptoEncapsulation: ERROR MsgComposeSecure not instantiated\n"
+      );
       throw Cr.NS_ERROR_FAILURE;
     }
 
-    if (this.useSmime)
-      return this.smimeCompose.beginCryptoEncapsulation(outStream, recipientList,
-        msgCompFields, msgIdentity,
-        sendReport, isDraft);
+    if (this.useSmime) {
+      return this.smimeCompose.beginCryptoEncapsulation(
+        outStream,
+        recipientList,
+        msgCompFields,
+        msgIdentity,
+        sendReport,
+        isDraft
+      );
+    }
 
-    if (!outStream) throw Cr.NS_ERROR_NULL_POINTER;
+    if (!outStream) {
+      throw Cr.NS_ERROR_NULL_POINTER;
+    }
 
     try {
-
       this.outStream = outStream;
       this.isDraft = isDraft;
 
       this.msgCompFields = msgCompFields;
-      this.outStringStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
+      this.outStringStream = Cc[
+        "@mozilla.org/io/string-input-stream;1"
+      ].createInstance(Ci.nsIStringInputStream);
 
-      var windowManager = Cc[APPSHELL_MEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+      var windowManager = Services.wm;
       this.win = windowManager.getMostRecentWindow(null);
 
       if (this.sendFlags & EnigmailConstants.SEND_VERBATIM) {
         this.recipientList = recipientList;
         this.msgIdentity = msgIdentity;
         this.msgCompFields = msgCompFields;
         this.inputMode = 2;
         return null;
       }
 
       if (this.sendFlags & EnigmailConstants.SEND_PGP_MIME) {
-
         if (this.sendFlags & EnigmailConstants.SEND_ENCRYPTED) {
           // applies to encrypted and signed & encrypted
           this.cryptoMode = MIME_ENCRYPTED;
-        }
-        else if (this.sendFlags & EnigmailConstants.SEND_SIGNED) {
+        } else if (this.sendFlags & EnigmailConstants.SEND_SIGNED) {
           this.cryptoMode = MIME_SIGNED;
 
           let hashAlgoObj = {};
-          if (EnigmailHash.determineAlgorithm(this.win,
+          if (
+            EnigmailHash.determineAlgorithm(
+              this.win,
               this.UIFlags,
               this.senderEmailAddr,
-              hashAlgoObj) === 0) {
+              hashAlgoObj
+            ) === 0
+          ) {
             this.hashAlgorithm = hashAlgoObj.value;
-          }
-          else {
-            if ("statusFlags" in hashAlgoObj && hashAlgoObj.statusFlags !== 0 && hashAlgoObj.errorMsg) {
+          } else {
+            if (
+              "statusFlags" in hashAlgoObj &&
+              hashAlgoObj.statusFlags !== 0 &&
+              hashAlgoObj.errorMsg
+            ) {
               EnigmailDialog.alert(this.win, hashAlgoObj.errorMsg);
             }
 
             throw Cr.NS_ERROR_FAILURE;
           }
         }
+      } else {
+        throw Cr.NS_ERROR_NOT_IMPLEMENTED;
       }
-      else
-        throw Cr.NS_ERROR_NOT_IMPLEMENTED;
 
       this.cryptoBoundary = EnigmailMime.createBoundary();
       this.startCryptoHeaders();
-
-    }
-    catch (ex) {
+    } catch (ex) {
       EnigmailLog.writeException("mimeEncrypt.js", ex);
-      throw (ex);
+      throw ex;
     }
 
     return null;
   },
 
-  startCryptoHeaders: function() {
+  startCryptoHeaders() {
     EnigmailLog.DEBUG("mimeEncrypt.js: startCryptoHeaders\n");
 
-    if (this.cryptoMode == MIME_SIGNED) this.signedHeaders1(false);
-    if (this.cryptoMode == MIME_ENCRYPTED) this.encryptedHeaders();
+    if (this.cryptoMode == MIME_SIGNED) {
+      this.signedHeaders1(false);
+    }
+    if (this.cryptoMode == MIME_ENCRYPTED) {
+      this.encryptedHeaders();
+    }
 
     this.writeSecureHeaders();
   },
 
-  writeSecureHeaders: function() {
+  writeSecureHeaders() {
     this.encHeader = EnigmailMime.createBoundary();
 
     let allHdr = "";
 
     if (this.sendFlags & EnigmailConstants.ENCRYPT_HEADERS) {
       let addrParser = jsmime.headerparser.parseAddressingHeader;
       let newsParser = function(s) {
         return jsmime.headerparser.parseStructuredHeader("Newsgroups", s);
       };
       let noParser = function(s) {
         return s;
       };
 
       let h = {
         from: {
           field: "From",
-          parser: addrParser
+          parser: addrParser,
         },
         replyTo: {
           field: "Reply-To",
-          parser: addrParser
+          parser: addrParser,
         },
         to: {
           field: "To",
-          parser: addrParser
+          parser: addrParser,
         },
         cc: {
           field: "Cc",
-          parser: addrParser
+          parser: addrParser,
         },
         newsgroups: {
           field: "Newsgroups",
-          parser: newsParser
+          parser: newsParser,
         },
         followupTo: {
           field: "Followup-To",
-          parser: addrParser
+          parser: addrParser,
         },
         messageId: {
           field: "Message-Id",
-          parser: noParser
+          parser: noParser,
         },
         subject: {
           field: "Subject",
-          parser: noParser
-        }
+          parser: noParser,
+        },
       };
 
       for (let i in h) {
         if (this.msgCompFields[i] && this.msgCompFields[i].length > 0) {
-          allHdr += jsmime.headeremitter.emitStructuredHeader(h[i].field, h[i].parser(this.msgCompFields[i]), {});
+          allHdr += jsmime.headeremitter.emitStructuredHeader(
+            h[i].field,
+            h[i].parser(this.msgCompFields[i]),
+            {}
+          );
         }
       }
 
-      if (this.cryptoMode == MIME_ENCRYPTED && this.originalSubject && this.originalSubject.length > 0) {
-        allHdr += jsmime.headeremitter.emitStructuredHeader("subject", this.originalSubject, {});
+      if (
+        this.cryptoMode == MIME_ENCRYPTED &&
+        this.originalSubject &&
+        this.originalSubject.length > 0
+      ) {
+        allHdr += jsmime.headeremitter.emitStructuredHeader(
+          "subject",
+          this.originalSubject,
+          {}
+        );
       }
 
       // special handling for references and in-reply-to
 
       if (this.originalReferences && this.originalReferences.length > 0) {
-        allHdr += jsmime.headeremitter.emitStructuredHeader("references", this.originalReferences, {});
+        allHdr += jsmime.headeremitter.emitStructuredHeader(
+          "references",
+          this.originalReferences,
+          {}
+        );
 
         let bracket = this.originalReferences.lastIndexOf("<");
         if (bracket >= 0) {
-          allHdr += jsmime.headeremitter.emitStructuredHeader("in-reply-to", this.originalReferences.substr(bracket), {});
+          allHdr += jsmime.headeremitter.emitStructuredHeader(
+            "in-reply-to",
+            this.originalReferences.substr(bracket),
+            {}
+          );
         }
       }
     }
 
     let w = `Content-Type: multipart/mixed; boundary="${this.encHeader}"`;
 
     if (allHdr.length > 0) {
       w += `;\r\n protected-headers="v1"\r\n${allHdr}`;
-    }
-    else {
-      w += '\r\n';
+    } else {
+      w += "\r\n";
     }
 
     w += this.getAutocryptGossip() + `\r\n--${this.encHeader}\r\n`;
     this.writeToPipe(w);
 
-    if (this.cryptoMode == MIME_SIGNED) this.writeOut(w);
+    if (this.cryptoMode == MIME_SIGNED) {
+      this.writeOut(w);
+    }
   },
 
-  getAutocryptGossip: function() {
+  getAutocryptGossip() {
     let gossip = "";
-    if (this.cryptoMode == MIME_ENCRYPTED &&
+    if (
+      this.cryptoMode == MIME_ENCRYPTED &&
       this.msgCompFields.hasHeader("autocrypt") &&
       this.keyMap &&
-      EnigmailFuncs.getNumberOfRecipients(this.msgCompFields) > 1) {
+      EnigmailFuncs.getNumberOfRecipients(this.msgCompFields) > 1
+    ) {
       for (let email in this.keyMap) {
         let keyObj = EnigmailKeyRing.getKeyById(this.keyMap[email]);
         if (keyObj) {
           let k = keyObj.getMinimalPubKey(email);
           if (k.exitCode === 0) {
-            let keyData = " " + k.keyData.replace(/(.{72})/g, "$1\r\n ").replace(/\r\n $/, "");
-            gossip += 'Autocrypt-Gossip: addr=' + email + '; keydata=\r\n' + keyData + "\r\n";
+            let keyData =
+              " " +
+              k.keyData.replace(/(.{72})/g, "$1\r\n ").replace(/\r\n $/, "");
+            gossip +=
+              "Autocrypt-Gossip: addr=" +
+              email +
+              "; keydata=\r\n" +
+              keyData +
+              "\r\n";
           }
         }
       }
     }
 
     return gossip;
   },
 
-  encryptedHeaders: function(isEightBit) {
+  encryptedHeaders(isEightBit) {
     EnigmailLog.DEBUG("mimeEncrypt.js: encryptedHeaders\n");
     let subj = "";
 
     if (this.sendFlags & EnigmailConstants.ENCRYPT_HEADERS) {
-      subj = jsmime.headeremitter.emitStructuredHeader("subject", EnigmailFuncs.getProtectedSubjectText(), {});
+      subj = jsmime.headeremitter.emitStructuredHeader(
+        "subject",
+        EnigmailFuncs.getProtectedSubjectText(),
+        {}
+      );
     }
 
-    this.writeOut(subj +
-      "Content-Type: multipart/encrypted;\r\n" +
-      " protocol=\"application/pgp-encrypted\";\r\n" +
-      " boundary=\"" + this.cryptoBoundary + "\"\r\n" +
-      "\r\n" +
-      "This is an OpenPGP/MIME encrypted message (RFC 4880 and 3156)\r\n" +
-      "--" + this.cryptoBoundary + "\r\n" +
-      "Content-Type: application/pgp-encrypted\r\n" +
-      "Content-Description: PGP/MIME version identification\r\n" +
-      "\r\n" +
-      "Version: 1\r\n" +
-      "\r\n" +
-      "--" + this.cryptoBoundary + "\r\n" +
-      "Content-Type: application/octet-stream; name=\"encrypted.asc\"\r\n" +
-      "Content-Description: OpenPGP encrypted message\r\n" +
-      "Content-Disposition: inline; filename=\"encrypted.asc\"\r\n" +
-      "\r\n");
+    this.writeOut(
+      subj +
+        "Content-Type: multipart/encrypted;\r\n" +
+        ' protocol="application/pgp-encrypted";\r\n' +
+        ' boundary="' +
+        this.cryptoBoundary +
+        '"\r\n' +
+        "\r\n" +
+        "This is an OpenPGP/MIME encrypted message (RFC 4880 and 3156)\r\n" +
+        "--" +
+        this.cryptoBoundary +
+        "\r\n" +
+        "Content-Type: application/pgp-encrypted\r\n" +
+        "Content-Description: PGP/MIME version identification\r\n" +
+        "\r\n" +
+        "Version: 1\r\n" +
+        "\r\n" +
+        "--" +
+        this.cryptoBoundary +
+        "\r\n" +
+        'Content-Type: application/octet-stream; name="encrypted.asc"\r\n' +
+        "Content-Description: OpenPGP encrypted message\r\n" +
+        'Content-Disposition: inline; filename="encrypted.asc"\r\n' +
+        "\r\n"
+    );
   },
 
-  signedHeaders1: function(isEightBit) {
+  signedHeaders1(isEightBit) {
     LOCAL_DEBUG("mimeEncrypt.js: signedHeaders1\n");
-    this.writeOut("Content-Type: multipart/signed; micalg=pgp-" +
-      this.hashAlgorithm.toLowerCase() +
-      ";\r\n" +
-      " protocol=\"application/pgp-signature\";\r\n" +
-      " boundary=\"" + this.cryptoBoundary + "\"\r\n" +
-      (isEightBit ? "Content-Transfer-Encoding: 8bit\r\n\r\n" : "\r\n") +
-      "This is an OpenPGP/MIME signed message (RFC 4880 and 3156)\r\n" +
-      "--" + this.cryptoBoundary + "\r\n");
+    this.writeOut(
+      "Content-Type: multipart/signed; micalg=pgp-" +
+        this.hashAlgorithm.toLowerCase() +
+        ";\r\n" +
+        ' protocol="application/pgp-signature";\r\n' +
+        ' boundary="' +
+        this.cryptoBoundary +
+        '"\r\n' +
+        (isEightBit ? "Content-Transfer-Encoding: 8bit\r\n\r\n" : "\r\n") +
+        "This is an OpenPGP/MIME signed message (RFC 4880 and 3156)\r\n" +
+        "--" +
+        this.cryptoBoundary +
+        "\r\n"
+    );
   },
 
-
-  signedHeaders2: function() {
+  signedHeaders2() {
     LOCAL_DEBUG("mimeEncrypt.js: signedHeaders2\n");
 
-    this.writeOut("\r\n--" + this.cryptoBoundary + "\r\n" +
-      "Content-Type: application/pgp-signature; name=\"signature.asc\"\r\n" +
-      "Content-Description: OpenPGP digital signature\r\n" +
-      "Content-Disposition: attachment; filename=\"signature.asc\"\r\n\r\n");
+    this.writeOut(
+      "\r\n--" +
+        this.cryptoBoundary +
+        "\r\n" +
+        'Content-Type: application/pgp-signature; name="signature.asc"\r\n' +
+        "Content-Description: OpenPGP digital signature\r\n" +
+        'Content-Disposition: attachment; filename="signature.asc"\r\n\r\n'
+    );
   },
 
-  finishCryptoHeaders: function() {
+  finishCryptoHeaders() {
     EnigmailLog.DEBUG("mimeEncrypt.js: finishCryptoHeaders\n");
 
     this.writeOut("\r\n--" + this.cryptoBoundary + "--\r\n");
   },
 
-  finishCryptoEncapsulation: function(abort, sendReport) {
+  finishCryptoEncapsulation(abort, sendReport) {
     EnigmailLog.DEBUG("mimeEncrypt.js: finishCryptoEncapsulation\n");
 
-    if (this.checkSMime && (!this.smimeCompose))
+    if (this.checkSMime && !this.smimeCompose) {
       throw Cr.NS_ERROR_NOT_INITIALIZED;
+    }
 
     if (this.useSmime) {
       this.smimeCompose.finishCryptoEncapsulation(abort, sendReport);
       return;
     }
 
     if ((this.sendFlags & EnigmailConstants.SEND_VERBATIM) !== 0) {
       this.flushOutput();
@@ -443,26 +527,28 @@ PgpMimeEncrypt.prototype = {
       if (this.cryptoMode == MIME_SIGNED) {
         this.writeOut("\r\n--" + this.encHeader + "--\r\n");
       }
     }
 
     let statusFlagsObj = {};
     let errorMsgObj = {};
     //let proc =
-    EnigmailEncryption.encryptMessageStart(this.win,
+    EnigmailEncryption.encryptMessageStart(
+      this.win,
       this.UIFlags,
       this.senderEmailAddr,
       this.recipients,
       this.bccRecipients,
       this.hashAlgorithm,
       this.sendFlags,
       this,
       statusFlagsObj,
-      errorMsgObj);
+      errorMsgObj
+    );
 
     //if (!proc) throw Cr.NS_ERROR_FAILURE;
 
     try {
       this.flushInput();
 
       /*
       if (!this.pipe) {
@@ -471,272 +557,306 @@ PgpMimeEncrypt.prototype = {
       else {
         this.pipe.close();
       }
       */
 
       // wait here for proc to terminate
       //proc.wait();
 
-      LOCAL_DEBUG("mimeEncrypt.js: finishCryptoEncapsulation: exitCode = " + this.exitCode + "\n");
+      LOCAL_DEBUG(
+        "mimeEncrypt.js: finishCryptoEncapsulation: exitCode = " +
+          this.exitCode +
+          "\n"
+      );
       if (this.exitCode !== 0) {
         throw Cr.NS_ERROR_FAILURE;
       }
 
       if (this.cryptoMode == MIME_SIGNED) {
         this.signedHeaders2();
       }
 
-      this.encryptedData = this.encryptedData.replace(/\r/g, "").replace(/\n/g, "\r\n"); // force CRLF
+      this.encryptedData = this.encryptedData
+        .replace(/\r/g, "")
+        .replace(/\n/g, "\r\n"); // force CRLF
       this.writeOut(this.encryptedData);
       this.finishCryptoHeaders();
       this.flushOutput();
-    }
-    catch (ex) {
+    } catch (ex) {
       EnigmailLog.writeException("mimeEncrypt.js", ex);
-      throw (ex);
+      throw ex;
     }
-
   },
 
-  mimeCryptoWriteBlock: function(buffer, length) {
-    if (gDebugLogLevel > 4)
+  mimeCryptoWriteBlock(buffer, length) {
+    if (gDebugLogLevel > 4) {
       LOCAL_DEBUG("mimeEncrypt.js: mimeCryptoWriteBlock: " + length + "\n");
+    }
 
-    if (this.checkSMime && (!this.smimeCompose))
+    if (this.checkSMime && !this.smimeCompose) {
       throw Cr.NS_ERROR_NOT_INITIALIZED;
+    }
 
-    if (this.useSmime) return this.smimeCompose.mimeCryptoWriteBlock(buffer, length);
+    if (this.useSmime) {
+      return this.smimeCompose.mimeCryptoWriteBlock(buffer, length);
+    }
 
     try {
       let line = buffer.substr(0, length);
       if (this.inputMode === 0) {
         if ((this.sendFlags & EnigmailConstants.SEND_VERBATIM) !== 0) {
           line = EnigmailData.decodeQuotedPrintable(line.replace("=\r\n", ""));
         }
 
-        if ((this.sendFlags & EnigmailConstants.SEND_VERBATIM) === 0 ||
-          line.match(/^(From|To|Subject|Message-ID|Date|User-Agent|MIME-Version):/i) === null) {
+        if (
+          (this.sendFlags & EnigmailConstants.SEND_VERBATIM) === 0 ||
+          line.match(
+            /^(From|To|Subject|Message-ID|Date|User-Agent|MIME-Version):/i
+          ) === null
+        ) {
           this.headerData += line;
         }
 
         if (line.replace(/[\r\n]/g, "").length === 0) {
           this.inputMode = 1;
 
           if (this.cryptoMode == MIME_ENCRYPTED) {
             if (!this.encHeader) {
               let ct = this.getHeader("content-type", false);
-              if ((ct.search(/text\/plain/i) === 0) || (ct.search(/text\/html/i) === 0)) {
+              if (
+                ct.search(/text\/plain/i) === 0 ||
+                ct.search(/text\/html/i) === 0
+              ) {
                 this.encapsulate = EnigmailMime.createBoundary();
-                this.writeToPipe('Content-Type: multipart/mixed; boundary="' +
-                  this.encapsulate + '"\r\n\r\n');
+                this.writeToPipe(
+                  'Content-Type: multipart/mixed; boundary="' +
+                    this.encapsulate +
+                    '"\r\n\r\n'
+                );
                 this.writeToPipe("--" + this.encapsulate + "\r\n");
               }
             }
-          }
-          else if (this.cryptoMode == MIME_SIGNED) {
+          } else if (this.cryptoMode == MIME_SIGNED) {
             let ct = this.getHeader("content-type", true);
             let hdr = EnigmailFuncs.getHeaderData(ct);
             hdr.boundary = hdr.boundary || "";
             hdr.boundary = hdr.boundary.replace(/['"]/g, "");
           }
 
           this.writeToPipe(this.headerData);
-          if (this.cryptoMode == MIME_SIGNED ||
-            (this.sendFlags & EnigmailConstants.SEND_VERBATIM) !== 0) {
+          if (
+            this.cryptoMode == MIME_SIGNED ||
+            (this.sendFlags & EnigmailConstants.SEND_VERBATIM) !== 0
+          ) {
             this.writeOut(this.headerData);
           }
         }
-
-      }
-      else if (this.inputMode == 1) {
+      } else if (this.inputMode == 1) {
         if (this.cryptoMode == MIME_SIGNED) {
           // special treatments for various special cases with PGP/MIME signed messages
           if (line.substr(0, 5) == "From ") {
             LOCAL_DEBUG("mimeEncrypt.js: added >From\n");
             this.writeToPipe(">");
           }
         }
 
         this.writeToPipe(line);
         if (this.cryptoMode == MIME_SIGNED) {
           this.writeOut(line);
+        } else if ((this.sendFlags & EnigmailConstants.SEND_VERBATIM) !== 0) {
+          this.writeOut(
+            EnigmailData.decodeQuotedPrintable(line.replace("=\r\n", ""))
+          );
         }
-        else if ((this.sendFlags & EnigmailConstants.SEND_VERBATIM) !== 0) {
-          this.writeOut(EnigmailData.decodeQuotedPrintable(line.replace("=\r\n", "")));
-        }
-      }
-      else if (this.inputMode == 2) {
+      } else if (this.inputMode == 2) {
         if (line.replace(/[\r\n]/g, "").length === 0) {
           this.inputMode = 0;
         }
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       EnigmailLog.writeException("mimeEncrypt.js", ex);
-      throw (ex);
+      throw ex;
     }
 
     return null;
   },
 
-  writeOut: function(str) {
-    if (gDebugLogLevel > 4)
+  writeOut(str) {
+    if (gDebugLogLevel > 4) {
       LOCAL_DEBUG("mimeEncrypt.js: writeOut: " + str.length + "\n");
+    }
 
     this.outQueue += str;
 
-    if (this.outQueue.length > maxBufferLen)
+    if (this.outQueue.length > maxBufferLen) {
       this.flushOutput();
+    }
   },
 
-  flushOutput: function() {
+  flushOutput() {
     LOCAL_DEBUG("mimeEncrypt.js: flushOutput: " + this.outQueue.length + "\n");
 
     this.outStringStream.setData(this.outQueue, this.outQueue.length);
-    var writeCount = this.outStream.writeFrom(this.outStringStream, this.outQueue.length);
+    var writeCount = this.outStream.writeFrom(
+      this.outStringStream,
+      this.outQueue.length
+    );
     if (writeCount < this.outQueue.length) {
-      LOCAL_DEBUG("mimeEncrypt.js: flushOutput: wrote " + writeCount + " instead of " + this.outQueue.length + " bytes\n");
+      LOCAL_DEBUG(
+        "mimeEncrypt.js: flushOutput: wrote " +
+          writeCount +
+          " instead of " +
+          this.outQueue.length +
+          " bytes\n"
+      );
     }
     this.outQueue = "";
   },
 
-  writeToPipe: function(str) {
-    if (gDebugLogLevel > 4)
+  writeToPipe(str) {
+    if (gDebugLogLevel > 4) {
       LOCAL_DEBUG("mimeEncrypt.js: writeToPipe: " + str.length + "\n");
+    }
 
     if (this.pipe) {
       this.pipeQueue += str;
-      if (this.pipeQueue.length > maxBufferLen)
+      if (this.pipeQueue.length > maxBufferLen) {
         this.flushInput();
+      }
+    } else {
+      this.pipeQueue += str;
     }
-    else
-      this.pipeQueue += str;
   },
 
-  flushInput: function() {
+  flushInput() {
     LOCAL_DEBUG("mimeEncrypt.js: flushInput\n");
-    if (!this.pipe) return;
+    if (!this.pipe) {
+      return;
+    }
     this.pipe.write(this.pipeQueue);
     this.pipeQueue = "";
   },
 
-  getHeader: function(hdrStr, fullHeader) {
-    var foundIndex = 0;
+  getHeader(hdrStr, fullHeader) {
     var res = "";
     var hdrLines = this.headerData.split(/[\r\n]+/);
     var i;
     for (i = 0; i < hdrLines.length; i++) {
       if (hdrLines[i].length > 0) {
         if (fullHeader && res !== "") {
           if (hdrLines[i].search(/^\s+/) === 0) {
             res += hdrLines[i].replace(/\s*[\r\n]*$/, "");
-          }
-          else
+          } else {
             return res;
-        }
-        else {
+          }
+        } else {
           let j = hdrLines[i].indexOf(":");
           if (j > 0) {
             let h = hdrLines[i].substr(0, j).replace(/\s*$/, "");
             let re = new RegExp("^" + hdrStr + "$", "i");
             if (h.search(re) === 0) {
-              foundIndex = 1;
               res = hdrLines[i].substr(j + 1).replace(/^\s*/, "");
-              if (!fullHeader) return res;
+              if (!fullHeader) {
+                return res;
+              }
             }
           }
         }
       }
     }
 
     return res;
   },
 
   getInputForEncryption() {
     return this.pipeQueue;
   },
-  
+
   addEncryptedOutput(s) {
     this.stdout(s);
   },
 
   // API for decryptMessage Listener
-  stdin: function(pipe) {
+  stdin(pipe) {
     LOCAL_DEBUG("mimeEncrypt.js: stdin\n");
     if (this.pipeQueue.length > 0) {
       pipe.write(this.pipeQueue);
       this.pipeQueue = "";
     }
     if (this.closePipe) {
       pipe.close();
-    }
-    else {
+    } else {
       this.pipe = pipe;
     }
   },
 
-  stdout: function(s) {
+  stdout(s) {
     LOCAL_DEBUG("mimeEncrypt.js: stdout:" + s.length + "\n");
     this.encryptedData += s;
     this.dataLength += s.length;
   },
 
-  stderr: function(s) {
+  stderr(s) {
     LOCAL_DEBUG("mimeEncrypt.js: stderr\n");
     this.statusStr += s;
   },
 
-  done: function(exitCode) {
+  done(exitCode) {
     EnigmailLog.DEBUG("mimeEncrypt.js: done: " + exitCode + "\n");
 
     let retStatusObj = {};
 
-    this.exitCode = EnigmailEncryption.encryptMessageEnd(this.senderEmailAddr,
+    this.exitCode = EnigmailEncryption.encryptMessageEnd(
+      this.senderEmailAddr,
       this.statusStr,
       exitCode,
       this.UIFlags,
       this.sendFlags,
       this.dataLength,
-      retStatusObj);
+      retStatusObj
+    );
 
-    if (this.exitCode !== 0)
+    if (this.exitCode !== 0) {
       EnigmailDialog.alert(this.win, retStatusObj.errorMsg);
+    }
   },
 };
 
-
 ////////////////////////////////////////////////////////////////////
 // General-purpose functions, not exported
 
-
 function LOCAL_DEBUG(str) {
-  if (gDebugLogLevel) EnigmailLog.DEBUG(str);
+  if (gDebugLogLevel) {
+    EnigmailLog.DEBUG(str);
+  }
 }
 
 function initModule() {
   EnigmailLog.DEBUG("mimeEncrypt.jsm: initModule()\n");
-  var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
+  var env = Cc["@mozilla.org/process/environment;1"].getService(
+    Ci.nsIEnvironment
+  );
   var nspr_log_modules = env.get("NSPR_LOG_MODULES");
   var matches = nspr_log_modules.match(/mimeEncrypt:(\d+)/);
 
-  if (matches && (matches.length > 1)) {
+  if (matches && matches.length > 1) {
     gDebugLogLevel = matches[1];
     LOCAL_DEBUG("mimeEncrypt.js: enabled debug logging\n");
   }
 }
 
 var EnigmailMimeEncrypt = {
   Handler: PgpMimeEncrypt,
 
-  startup: function(reason) {
+  startup(reason) {
     initModule();
   },
-  shutdown: function(reason) {},
+  shutdown(reason) {},
 
-  createMimeEncrypt: function(sMimeSecurityInfo) {
+  createMimeEncrypt(sMimeSecurityInfo) {
     return new PgpMimeEncrypt(sMimeSecurityInfo);
   },
 
-  isEnigmailCompField: function(obj) {
+  isEnigmailCompField(obj) {
     return obj instanceof PgpMimeEncrypt;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/mimeVerify.jsm
+++ b/mail/extensions/openpgp/content/modules/mimeVerify.jsm
@@ -1,117 +1,148 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailVerify"];
 
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+
 /**
  *  Module for handling PGP/MIME signed messages
  *  implemented as JS module
  */
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailDecryption = ChromeUtils.import("chrome://openpgp/content/modules/decryption.jsm").EnigmailDecryption;
-const EnigmailSingletons = ChromeUtils.import("chrome://openpgp/content/modules/singletons.jsm").EnigmailSingletons;
-const EnigmailHttpProxy = ChromeUtils.import("chrome://openpgp/content/modules/httpProxy.jsm").EnigmailHttpProxy;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailDecryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/decryption.jsm"
+).EnigmailDecryption;
+const EnigmailSingletons = ChromeUtils.import(
+  "chrome://openpgp/content/modules/singletons.jsm"
+).EnigmailSingletons;
+const EnigmailHttpProxy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/httpProxy.jsm"
+).EnigmailHttpProxy;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
-const APPSHELL_MEDIATOR_CONTRACTID = "@mozilla.org/appshell/window-mediator;1";
 const PGPMIME_PROTO = "application/pgp-signature";
 
-const maxBufferLen = 102400;
-
 var gDebugLog = false;
 
 // MimeVerify Constructor
 function MimeVerify(protocol) {
   if (!protocol) {
     protocol = PGPMIME_PROTO;
   }
 
   this.protocol = protocol;
   this.verifyEmbedded = false;
   this.partiallySigned = false;
   this.exitCode = null;
-  this.inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
+  this.inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+    Ci.nsIScriptableInputStream
+  );
 
   this.onDataAvailable = this.onDataAvailable68;
 }
 
-
 var EnigmailVerify = {
   lastMsgWindow: null,
   lastMsgUri: null,
   manualMsgUri: null,
 
   currentCtHandler: EnigmailConstants.MIME_HANDLER_UNDEF,
 
-  setMsgWindow: function(msgWindow, msgUriSpec) {
+  setMsgWindow(msgWindow, msgUriSpec) {
     LOCAL_DEBUG("mimeVerify.jsm: setMsgWindow: " + msgUriSpec + "\n");
 
     this.lastMsgWindow = msgWindow;
     this.lastMsgUri = msgUriSpec;
   },
 
-  newVerifier: function(protocol) {
-    EnigmailLog.DEBUG("mimeVerify.jsm: newVerifier: " + (protocol || "null") + "\n");
+  newVerifier(protocol) {
+    EnigmailLog.DEBUG(
+      "mimeVerify.jsm: newVerifier: " + (protocol || "null") + "\n"
+    );
 
     let v = new MimeVerify(protocol);
     return v;
   },
 
-  setManualUri: function(msgUriSpec) {
+  setManualUri(msgUriSpec) {
     LOCAL_DEBUG("mimeVerify.jsm: setManualUri: " + msgUriSpec + "\n");
     this.manualMsgUri = msgUriSpec;
   },
 
-  getManualUri: function() {
+  getManualUri() {
     EnigmailLog.DEBUG("mimeVerify.jsm: getManualUri\n");
     return this.manualMsgUri;
   },
 
   /***
    * register a PGP/MIME verify object the same way PGP/MIME encrypted mail is handled
    */
-  registerContentTypeHandler: function() {
+  registerContentTypeHandler() {
     EnigmailLog.DEBUG("mimeVerify.jsm: registerContentTypeHandler\n");
     let reg = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
 
-    let pgpMimeClass = Components.classes["@mozilla.org/mimecth;1?type=multipart/encrypted"];
+    let pgpMimeClass = Cc["@mozilla.org/mimecth;1?type=multipart/encrypted"];
 
     reg.registerFactory(
       pgpMimeClass,
       "Enigmail PGP/MIME verification",
       "@mozilla.org/mimecth;1?type=multipart/signed",
-      null);
+      null
+    );
     this.currentCtHandler = EnigmailConstants.MIME_HANDLER_PGPMIME;
   },
 
-  unregisterContentTypeHandler: function() {
+  unregisterContentTypeHandler() {
     EnigmailLog.DEBUG("mimeVerify.jsm: unregisterContentTypeHandler\n");
     let reg = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
 
-    let sMimeClass = Components.classes["@mozilla.org/nsCMSDecoder;1"];
-    reg.registerFactory(sMimeClass, "S/MIME verification", "@mozilla.org/mimecth;1?type=multipart/signed", null);
+    let sMimeClass = Cc["@mozilla.org/nsCMSDecoder;1"];
+    reg.registerFactory(
+      sMimeClass,
+      "S/MIME verification",
+      "@mozilla.org/mimecth;1?type=multipart/signed",
+      null
+    );
     this.currentCtHandler = EnigmailConstants.MIME_HANDLER_SMIME;
-  }
-
+  },
 };
 
-
 // MimeVerify implementation
 // verify the signature of PGP/MIME signed messages
 MimeVerify.prototype = {
   dataCount: 0,
   foundMsg: false,
   startMsgStr: "",
   msgWindow: null,
   msgUriSpec: null,
@@ -119,84 +150,92 @@ MimeVerify.prototype = {
   window: null,
   inStream: null,
   sigFile: null,
   sigData: "",
   mimePartNumber: "",
 
   QueryInterface: EnigmailCompat.generateQI([Ci.nsIStreamListener]),
 
-  startStreaming: function(window, msgWindow, msgUriSpec) {
+  startStreaming(window, msgWindow, msgUriSpec) {
     LOCAL_DEBUG("mimeVerify.jsm: startStreaming\n");
 
     this.msgWindow = msgWindow;
     this.msgUriSpec = msgUriSpec;
     this.window = window;
     var messenger = Cc["@mozilla.org/messenger;1"].getService(Ci.nsIMessenger);
     var msgSvc = messenger.messageServiceFromURI(this.msgUriSpec);
 
-    msgSvc.streamMessage(this.msgUriSpec,
+    msgSvc.streamMessage(
+      this.msgUriSpec,
       this,
       this.msgWindow,
       null,
       false,
       null,
-      false);
+      false
+    );
   },
 
-  verifyData: function(window, msgWindow, msgUriSpec, data) {
+  verifyData(window, msgWindow, msgUriSpec, data) {
     LOCAL_DEBUG("mimeVerify.jsm: streamFromChannel\n");
 
     this.msgWindow = msgWindow;
     this.msgUriSpec = msgUriSpec;
     this.window = window;
     this.onStartRequest();
     this.onTextData(data);
     this.onStopRequest();
   },
 
-  parseContentType: function() {
+  parseContentType() {
     let contentTypeLine = this.mimeSvc.contentType;
 
     // Eat up CRLF's.
     contentTypeLine = contentTypeLine.replace(/[\r\n]/g, "");
-    EnigmailLog.DEBUG("mimeVerify.jsm: parseContentType: " + contentTypeLine + "\n");
-
-    let protoRx = RegExp("protocol\\s*=\\s*[\\'\\\"]" + this.protocol + "[\\\"\\']", "i");
+    EnigmailLog.DEBUG(
+      "mimeVerify.jsm: parseContentType: " + contentTypeLine + "\n"
+    );
 
-    if (contentTypeLine.search(/multipart\/signed/i) >= 0 &&
-      contentTypeLine.search(protoRx) > 0) {
+    let protoRx = RegExp(
+      "protocol\\s*=\\s*[\\'\\\"]" + this.protocol + "[\\\"\\']",
+      "i"
+    );
 
-      EnigmailLog.DEBUG("mimeVerify.jsm: parseContentType: found MIME signed message\n");
+    if (
+      contentTypeLine.search(/multipart\/signed/i) >= 0 &&
+      contentTypeLine.search(protoRx) > 0
+    ) {
+      EnigmailLog.DEBUG(
+        "mimeVerify.jsm: parseContentType: found MIME signed message\n"
+      );
       this.foundMsg = true;
       let hdr = EnigmailFuncs.getHeaderData(contentTypeLine);
       hdr.boundary = hdr.boundary || "";
       hdr.micalg = hdr.micalg || "";
       this.boundary = hdr.boundary.replace(/['"]/g, "");
     }
   },
 
-  onStartRequest: function(request, uri) {
+  onStartRequest(request, uri) {
     EnigmailLog.DEBUG("mimeVerify.jsm: onStartRequest\n"); // always log this one
 
     this.mimeSvc = request.QueryInterface(Ci.nsIPgpMimeProxy);
     this.msgUriSpec = EnigmailVerify.lastMsgUri;
 
     if ("mimePart" in this.mimeSvc) {
       this.mimePartNumber = this.mimeSvc.mimePart;
     } else {
       this.mimePartNumber = "";
     }
 
     if ("messageURI" in this.mimeSvc) {
       this.uri = this.mimeSvc.messageURI;
-    } else {
-      if (uri) {
-        this.uri = uri.QueryInterface(Ci.nsIURI);
-      }
+    } else if (uri) {
+      this.uri = uri.QueryInterface(Ci.nsIURI);
     }
 
     this.dataCount = 0;
     this.foundMsg = false;
     this.backgroundJob = false;
     this.startMsgStr = "";
     this.boundary = "";
     this.proc = null;
@@ -211,400 +250,476 @@ MimeVerify.prototype = {
     this.statusDisplayed = false;
     this.protectedHeaders = null;
     this.parseContentType();
   },
 
   /**
    * onDataAvailable for TB <= 66
    */
-  onDataAvailable60: function(req, ctxt, stream, offset, count) {
+  onDataAvailable60(req, ctxt, stream, offset, count) {
     LOCAL_DEBUG("mimeVerify.jsm: onDataAvailable60: " + count + "\n");
     if (count > 0) {
       this.inStream.init(stream);
       var data = this.inStream.read(count);
       this.onTextData(data);
     }
   },
 
   /**
    * onDataAvailable for TB >= 67
    */
-  onDataAvailable68: function(req, stream, offset, count) {
+  onDataAvailable68(req, stream, offset, count) {
     LOCAL_DEBUG("mimeVerify.jsm: onDataAvailable68: " + count + "\n");
     if (count > 0) {
       this.inStream.init(stream);
       var data = this.inStream.read(count);
       this.onTextData(data);
     }
   },
 
-  onTextData: function(data) {
+  onTextData(data) {
     LOCAL_DEBUG("mimeVerify.jsm: onTextData\n");
 
     this.dataCount += data.length;
 
     this.keepData += data;
     if (this.readMode === 0) {
       // header data
       let i = this.findNextMimePart();
       if (i >= 0) {
         i += 2 + this.boundary.length;
         if (this.keepData[i] == "\n") {
           ++i;
         } else if (this.keepData[i] == "\r") {
           ++i;
-          if (this.keepData[i] == "\n") ++i;
+          if (this.keepData[i] == "\n") {
+            ++i;
+          }
         }
 
         this.keepData = this.keepData.substr(i);
         data = this.keepData;
         this.readMode = 1;
       } else {
         this.keepData = data.substr(-this.boundary.length - 3);
       }
     }
 
     if (this.readMode === 1) {
       // "real data"
-      if (data.indexOf("-") >= 0) { // only check current line for speed reasons
+      if (data.includes("-")) {
+        // only check current line for speed reasons
         let i = this.findNextMimePart();
         if (i >= 0) {
           // end of "read data found"
-          if (this.keepData[i - 2] == '\r' && this.keepData[i - 1] == '\n') {
+          if (this.keepData[i - 2] == "\r" && this.keepData[i - 1] == "\n") {
             --i;
           }
 
           this.signedData = this.keepData.substr(0, i - 1);
           this.keepData = this.keepData.substr(i);
           this.readMode = 2;
         }
-      } else
+      } else {
         return;
+      }
     }
 
     if (this.readMode === 2) {
       let i = this.keepData.indexOf("--" + this.boundary + "--");
       if (i >= 0) {
         // ensure that we keep everything until we got the "end" boundary
-        if (this.keepData[i - 2] == '\r' && this.keepData[i - 1] == '\n') {
+        if (this.keepData[i - 2] == "\r" && this.keepData[i - 1] == "\n") {
           --i;
         }
         this.keepData = this.keepData.substr(0, i - 1);
         this.readMode = 3;
       }
     }
 
     if (this.readMode === 3) {
       // signature data
       if (this.protocol === PGPMIME_PROTO) {
         let xferEnc = this.getContentTransferEncoding();
         if (xferEnc.search(/base64/i) >= 0) {
           let bound = this.getBodyPart();
-          this.keepData = EnigmailData.decodeBase64(this.keepData.substring(bound.start, bound.end)) + "\n";
+          this.keepData =
+            EnigmailData.decodeBase64(
+              this.keepData.substring(bound.start, bound.end)
+            ) + "\n";
         } else if (xferEnc.search(/quoted-printable/i) >= 0) {
           let bound = this.getBodyPart();
           let qp = this.keepData.substring(bound.start, bound.end);
           this.keepData = EnigmailData.decodeQuotedPrintable(qp) + "\n";
         }
 
         // extract signature data
         let s = Math.max(this.keepData.search(/^-----BEGIN PGP /m), 0);
-        let e = Math.max(this.keepData.search(/^-----END PGP /m), this.keepData.length - 30);
+        let e = Math.max(
+          this.keepData.search(/^-----END PGP /m),
+          this.keepData.length - 30
+        );
         this.sigData = this.keepData.substring(s, e + 30);
       } else {
         this.sigData = "";
       }
 
       this.keepData = "";
       this.readMode = 4; // ignore any further data
     }
-
   },
 
-  getBodyPart: function() {
+  getBodyPart() {
     let start = this.keepData.search(/(\n\n|\r\n\r\n)/);
     if (start < 0) {
       start = 0;
     }
     let end = this.keepData.indexOf("--" + this.boundary + "--") - 1;
     if (end < 0) {
       end = this.keepData.length;
     }
 
     return {
-      start: start,
-      end: end
+      start,
+      end,
     };
   },
 
   // determine content-transfer encoding of mime part, assuming that whole
   // message is in this.keepData
-  getContentTransferEncoding: function() {
+  getContentTransferEncoding() {
     let enc = "7bit";
-    let m = this.keepData.match(/^(content-transfer-encoding:)(.*)$/mi);
+    let m = this.keepData.match(/^(content-transfer-encoding:)(.*)$/im);
     if (m && m.length > 2) {
       enc = m[2].trim().toLowerCase();
     }
 
     return enc;
   },
 
-
-  findNextMimePart: function() {
+  findNextMimePart() {
     let startOk = false;
     let endOk = false;
 
     let i = this.keepData.indexOf("--" + this.boundary);
-    if (i === 0) startOk = true;
+    if (i === 0) {
+      startOk = true;
+    }
     if (i > 0) {
-      if (this.keepData[i - 1] == '\r' || this.keepData[i - 1] == '\n') startOk = true;
+      if (this.keepData[i - 1] == "\r" || this.keepData[i - 1] == "\n") {
+        startOk = true;
+      }
     }
 
-    if (!startOk) return -1;
+    if (!startOk) {
+      return -1;
+    }
 
     if (i + this.boundary.length + 2 < this.keepData.length) {
-      if (this.keepData[i + this.boundary.length + 2] == '\r' ||
-        this.keepData[i + this.boundary.length + 2] == '\n' ||
-        this.keepData.substr(i + this.boundary.length + 2, 2) == '--') endOk = true;
+      if (
+        this.keepData[i + this.boundary.length + 2] == "\r" ||
+        this.keepData[i + this.boundary.length + 2] == "\n" ||
+        this.keepData.substr(i + this.boundary.length + 2, 2) == "--"
+      ) {
+        endOk = true;
+      }
     }
     // else
     // endOk = true;
 
     if (i >= 0 && startOk && endOk) {
       return i;
     }
     return -1;
   },
 
-  onStopRequest: function() {
+  onStopRequest() {
     EnigmailLog.DEBUG("mimeVerify.jsm: onStopRequest\n");
 
     this.msgWindow = EnigmailVerify.lastMsgWindow;
     this.msgUriSpec = EnigmailVerify.lastMsgUri;
 
     let url = {};
 
     this.backgroundJob = false;
 
-
     // don't try to verify if no message found
     // if (this.verifyEmbedded && (!this.foundMsg)) return; // TODO - check
 
     if (this.readMode < 4) {
       // we got incomplete data; simply return what we got
-      this.returnData(this.signedData.length > 0 ? this.signedData : this.keepData);
+      this.returnData(
+        this.signedData.length > 0 ? this.signedData : this.keepData
+      );
 
       return;
     }
 
-    this.protectedHeaders = EnigmailMime.extractProtectedHeaders(this.signedData);
+    this.protectedHeaders = EnigmailMime.extractProtectedHeaders(
+      this.signedData
+    );
 
-    if (this.protectedHeaders && this.protectedHeaders.startPos >= 0 && this.protectedHeaders.endPos > this.protectedHeaders.startPos) {
-      let r = this.signedData.substr(0, this.protectedHeaders.startPos) + this.signedData.substr(this.protectedHeaders.endPos);
+    if (
+      this.protectedHeaders &&
+      this.protectedHeaders.startPos >= 0 &&
+      this.protectedHeaders.endPos > this.protectedHeaders.startPos
+    ) {
+      let r =
+        this.signedData.substr(0, this.protectedHeaders.startPos) +
+        this.signedData.substr(this.protectedHeaders.endPos);
       this.returnData(r);
     } else {
       this.returnData(this.signedData);
     }
 
     // return if not verifying first mime part
-    if (this.mimePartNumber.length > 0 && this.mimePartNumber.search(/^1(\.1)?$/) < 0) return;
+    if (
+      this.mimePartNumber.length > 0 &&
+      this.mimePartNumber.search(/^1(\.1)?$/) < 0
+    ) {
+      return;
+    }
 
     if (this.uri) {
       // return if not decrypting currently displayed message (except if
       // printing, replying, etc)
 
-      this.backgroundJob = (this.uri.spec.search(/[&?]header=(print|quotebody|enigmailConvert)/) >= 0);
+      this.backgroundJob =
+        this.uri.spec.search(/[&?]header=(print|quotebody|enigmailConvert)/) >=
+        0;
 
       try {
-        var messenger = Cc["@mozilla.org/messenger;1"].getService(Ci.nsIMessenger);
-
         if (!EnigmailPrefs.getPref("autoDecrypt")) {
           // "decrypt manually" mode
           let manUrl = {};
 
           if (EnigmailVerify.getManualUri()) {
-            manUrl = EnigmailCompat.getUrlFromUriSpec(EnigmailVerify.getManualUri());
+            manUrl = EnigmailCompat.getUrlFromUriSpec(
+              EnigmailVerify.getManualUri()
+            );
           } else {
             manUrl = {
-              spec: "enigmail://invalid/message"
+              spec: "enigmail://invalid/message",
             };
           }
 
           // print a message if not message explicitly decrypted
-          let currUrlSpec = this.uri.spec.replace(/(\?.*)(number=[0-9]*)(&.*)?$/, "?$2");
-          let manUrlSpec = manUrl.spec.replace(/(\?.*)(number=[0-9]*)(&.*)?$/, "?$2");
+          let currUrlSpec = this.uri.spec.replace(
+            /(\?.*)(number=[0-9]*)(&.*)?$/,
+            "?$2"
+          );
+          let manUrlSpec = manUrl.spec.replace(
+            /(\?.*)(number=[0-9]*)(&.*)?$/,
+            "?$2"
+          );
 
-
-          if ((!this.backgroundJob) && currUrlSpec != manUrlSpec) {
+          if (!this.backgroundJob && currUrlSpec != manUrlSpec) {
             return; // this.handleManualDecrypt();
           }
         }
 
         if (this.msgUriSpec) {
           url = EnigmailCompat.getUrlFromUriSpec(this.msgUriSpec);
         }
 
-        if (this.uri.spec.search(/[&?]header=[a-zA-Z0-9]*$/) < 0 &&
+        if (
+          this.uri.spec.search(/[&?]header=[a-zA-Z0-9]*$/) < 0 &&
           this.uri.spec.search(/[&?]part=[.0-9]+/) < 0 &&
-          this.uri.spec.search(/[&?]examineEncryptedParts=true/) < 0) {
-
-          if (this.uri.spec.search(/[&?]header=filter&.*$/) > 0)
+          this.uri.spec.search(/[&?]examineEncryptedParts=true/) < 0
+        ) {
+          if (this.uri.spec.search(/[&?]header=filter&.*$/) > 0) {
             return;
+          }
 
           if (this.uri && url) {
-
-            if ("path" in url) {
-              // TB < 57
-              if (url.host !== this.uri.host ||
-                url.path !== this.uri.path)
-                return;
-            } else {
-              // TB >= 57
-              if (url.host !== this.uri.host ||
-                url.pathQueryRef !== this.uri.pathQueryRef)
-                return;
+            if (
+              url.host !== this.uri.host ||
+              url.pathQueryRef !== this.uri.pathQueryRef
+            ) {
+              return;
             }
           }
         }
       } catch (ex) {
         EnigmailLog.writeException("mimeVerify.jsm", ex);
-        EnigmailLog.DEBUG("mimeVerify.jsm: error while processing " + this.msgUriSpec + "\n");
+        EnigmailLog.DEBUG(
+          "mimeVerify.jsm: error while processing " + this.msgUriSpec + "\n"
+        );
       }
     }
 
     if (this.protocol === PGPMIME_PROTO) {
-      var windowManager = Cc[APPSHELL_MEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+      var windowManager = Services.wm;
       var win = windowManager.getMostRecentWindow(null);
 
       // create temp file holding signature data
       this.sigFile = EnigmailFiles.getTempDirObj();
       this.sigFile.append("data.sig");
       this.sigFile.createUnique(this.sigFile.NORMAL_FILE_TYPE, 0x180);
       EnigmailFiles.writeFileContents(this.sigFile, this.sigData, 0x180);
 
-      if (!EnigmailDecryption.isReady(win)) return;
+      if (!EnigmailDecryption.isReady(win)) {
+        return;
+      }
 
-
-      let sigFileName = EnigmailFiles.getEscapedFilename(EnigmailFiles.getFilePath(this.sigFile));
+      let sigFileName = EnigmailFiles.getEscapedFilename(
+        EnigmailFiles.getFilePath(this.sigFile)
+      );
       let keyserver = EnigmailPrefs.getPref("autoKeyRetrieve");
       let options = {
-        keyserver: keyserver,
+        keyserver,
         keyserverProxy: EnigmailHttpProxy.getHttpProxy(keyserver),
         fromAddr: EnigmailDecryption.getFromAddr(win),
-        mimeSignatureFile: sigFileName
+        mimeSignatureFile: sigFileName,
       };
       const cApi = EnigmailCryptoAPI();
 
       // ensure all lines end with CRLF as specified in RFC 3156, section 5
       if (this.signedData.search(/[^\r]\n/) >= 0) {
-        this.signedData = this.signedData.replace(/\r\n/g, "\n").replace(/\n/g, "\r\n");
+        this.signedData = this.signedData
+          .replace(/\r\n/g, "\n")
+          .replace(/\n/g, "\r\n");
       }
 
       this.returnStatus = cApi.sync(cApi.verifyMime(this.signedData, options));
       this.exitCode = this.returnStatus.exitCode;
 
-      if (this.partiallySigned)
+      if (this.partiallySigned) {
         this.returnStatus.statusFlags |= EnigmailConstants.PARTIALLY_PGP;
+      }
 
       this.displayStatus();
 
-      if (this.sigFile) this.sigFile.remove(false);
+      if (this.sigFile) {
+        this.sigFile.remove(false);
+      }
     }
   },
 
   // return data to libMime
-  returnData: function(data) {
-    EnigmailLog.DEBUG("mimeVerify.jsm: returnData: " + data.length + " bytes\n");
+  returnData(data) {
+    EnigmailLog.DEBUG(
+      "mimeVerify.jsm: returnData: " + data.length + " bytes\n"
+    );
 
     let m = data.match(/^(content-type: +)([\w/]+)/im);
     if (m && m.length >= 3) {
       let contentType = m[2];
       if (contentType.search(/^text/i) === 0) {
         // add multipart/mixed boundary to work around TB bug (empty forwarded message)
         let bound = EnigmailMime.createBoundary();
-        data = 'Content-Type: multipart/mixed; boundary="' + bound + '"\n' +
-          'Content-Disposition: inline\n\n--' +
-          bound + '\n' +
+        data =
+          'Content-Type: multipart/mixed; boundary="' +
+          bound +
+          '"\n' +
+          "Content-Disposition: inline\n\n--" +
+          bound +
+          "\n" +
           data +
-          '\n--' + bound + '--\n';
+          "\n--" +
+          bound +
+          "--\n";
       }
     }
 
     if ("outputDecryptedData" in this.mimeSvc) {
       // TB >= 57
       this.mimeSvc.outputDecryptedData(data, data.length);
     } else {
-      let gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
+      let gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
+        Ci.nsIStringInputStream
+      );
       gConv.setData(data, data.length);
       try {
         this.mimeSvc.onStartRequest(null, null);
         this.mimeSvc.onDataAvailable(null, null, gConv, 0, data.length);
         this.mimeSvc.onStopRequest(null, null, 0);
       } catch (ex) {
-        EnigmailLog.ERROR("mimeVerify.jsm: returnData(): mimeSvc.onDataAvailable failed:\n" + ex.toString());
+        EnigmailLog.ERROR(
+          "mimeVerify.jsm: returnData(): mimeSvc.onDataAvailable failed:\n" +
+            ex.toString()
+        );
       }
     }
   },
 
-  setMsgWindow: function(msgWindow, msgUriSpec) {
+  setMsgWindow(msgWindow, msgUriSpec) {
     EnigmailLog.DEBUG("mimeVerify.jsm: setMsgWindow: " + msgUriSpec + "\n");
 
     if (!this.msgWindow) {
       this.msgWindow = msgWindow;
       this.msgUriSpec = msgUriSpec;
     }
   },
 
-  displayStatus: function() {
+  displayStatus() {
     EnigmailLog.DEBUG("mimeVerify.jsm: displayStatus\n");
-    if (this.exitCode === null || this.msgWindow === null || this.statusDisplayed || this.backgroundJob)
+    if (
+      this.exitCode === null ||
+      this.msgWindow === null ||
+      this.statusDisplayed ||
+      this.backgroundJob
+    ) {
       return;
+    }
 
     try {
       LOCAL_DEBUG("mimeVerify.jsm: displayStatus displaying result\n");
       let headerSink = EnigmailSingletons.messageReader;
 
       if (this.protectedHeaders) {
-        headerSink.processDecryptionResult(this.uri, "modifyMessageHeaders", JSON.stringify(this.protectedHeaders.newHeaders), this.mimePartNumber);
+        headerSink.processDecryptionResult(
+          this.uri,
+          "modifyMessageHeaders",
+          JSON.stringify(this.protectedHeaders.newHeaders),
+          this.mimePartNumber
+        );
       }
 
       if (headerSink) {
-        headerSink.updateSecurityStatus(this.lastMsgUri,
+        headerSink.updateSecurityStatus(
+          this.lastMsgUri,
           this.exitCode,
           this.returnStatus.statusFlags,
           this.returnStatus.keyId,
           this.returnStatus.userId,
           this.returnStatus.sigDetails,
           this.returnStatus.errorMsg,
           this.returnStatus.blockSeparation,
           this.uri,
           JSON.stringify({
-            encryptedTo: this.returnStatus.encToDetails
+            encryptedTo: this.returnStatus.encToDetails,
           }),
-          this.mimePartNumber);
+          this.mimePartNumber
+        );
       }
       this.statusDisplayed = true;
     } catch (ex) {
       EnigmailLog.writeException("mimeVerify.jsm", ex);
     }
-  }
+  },
 };
 
-
 ////////////////////////////////////////////////////////////////////
 // General-purpose functions, not exported
 
 function LOCAL_DEBUG(str) {
-  if (gDebugLog) EnigmailLog.DEBUG(str);
+  if (gDebugLog) {
+    EnigmailLog.DEBUG(str);
+  }
 }
 
 function initModule() {
-  var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
+  var env = Cc["@mozilla.org/process/environment;1"].getService(
+    Ci.nsIEnvironment
+  );
   var nspr_log_modules = env.get("NSPR_LOG_MODULES");
   var matches = nspr_log_modules.match(/mimeVerify:(\d+)/);
 
-  if (matches && (matches.length > 1)) {
-    if (matches[1] > 2) gDebugLog = true;
+  if (matches && matches.length > 1) {
+    if (matches[1] > 2) {
+      gDebugLog = true;
+    }
   }
 }
 
 initModule();
--- a/mail/extensions/openpgp/content/modules/msgRead.jsm
+++ b/mail/extensions/openpgp/content/modules/msgRead.jsm
@@ -7,166 +7,195 @@
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailMsgRead"];
 
 /**
  * Message-reading related functions
  */
 
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
 
 const ExtraHeaders = ["autocrypt", "openpgp"];
 
 var EnigmailMsgRead = {
   /**
    * Ensure that Thunderbird prepares certain headers during message reading
    */
-  ensureExtraAddonHeaders: function() {
+  ensureExtraAddonHeaders() {
     let r = EnigmailPrefs.getPrefRoot();
 
     // is the Mozilla Platform number >= 59?
     const PREF_NAME = "mailnews.headers.extraAddonHeaders";
 
     try {
       let hdr = r.getCharPref(PREF_NAME);
 
-      if (hdr !== "*") { // do nothing if extraAddonHeaders is "*" (all headers)
+      if (hdr !== "*") {
+        // do nothing if extraAddonHeaders is "*" (all headers)
         for (let h of ExtraHeaders) {
-          let sr = new RegExp("\\b" + h + "\\b", "i");
+          // TODO: Was it a bug that variable sr wasn't used?
+          // let sr = new RegExp("\\b" + h + "\\b", "i");
           if (hdr.search(h) < 0) {
-            if (hdr.length > 0) hdr += " ";
+            if (hdr.length > 0) {
+              hdr += " ";
+            }
             hdr += h;
           }
         }
 
         r.setCharPref(PREF_NAME, hdr);
       }
-    }
-    catch (x) {}
+    } catch (x) {}
   },
 
   /**
    * Get a mail URL from a uriSpec
    *
    * @param uriSpec: String - URI of the desired message
    *
    * @return Object: nsIURL or nsIMsgMailNewsUrl object
    */
-  getUrlFromUriSpec: function(uriSpec) {
+  getUrlFromUriSpec(uriSpec) {
     return EnigmailCompat.getUrlFromUriSpec(uriSpec);
   },
 
   /**
    * Determine if an attachment is possibly signed
    */
-  checkSignedAttachment: function(attachmentObj, index, currentAttachments) {
+  checkSignedAttachment(attachmentObj, index, currentAttachments) {
     function escapeRegex(string) {
-      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
+      return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
     }
 
     var attachmentList;
     if (index !== null) {
       attachmentList = attachmentObj;
-    }
-    else {
+    } else {
       attachmentList = currentAttachments;
       for (let i = 0; i < attachmentList.length; i++) {
         if (attachmentList[i].url == attachmentObj.url) {
           index = i;
           break;
         }
       }
-      if (index === null) return false;
+      if (index === null) {
+        return false;
+      }
     }
 
     var signed = false;
     var findFile;
 
-    var attName = this.getAttachmentName(attachmentList[index]).toLowerCase().replace(/\+/g, "\\+");
+    var attName = this.getAttachmentName(attachmentList[index])
+      .toLowerCase()
+      .replace(/\+/g, "\\+");
 
     // check if filename is a signature
-    if ((this.getAttachmentName(attachmentList[index]).search(/\.(sig|asc)$/i) > 0) ||
-      (attachmentList[index].contentType.match(/^application\/pgp-signature/i))) {
+    if (
+      this.getAttachmentName(attachmentList[index]).search(/\.(sig|asc)$/i) >
+        0 ||
+      attachmentList[index].contentType.match(/^application\/pgp-signature/i)
+    ) {
       findFile = new RegExp(escapeRegex(attName.replace(/\.(sig|asc)$/, "")));
-    }
-    else if (attName.search(/\.pgp$/i) > 0) {
-      findFile = new RegExp(escapeRegex(attName.replace(/\.pgp$/, "")) + "(\\.pgp)?\\.(sig|asc)$");
-    }
-    else {
+    } else if (attName.search(/\.pgp$/i) > 0) {
+      findFile = new RegExp(
+        escapeRegex(attName.replace(/\.pgp$/, "")) + "(\\.pgp)?\\.(sig|asc)$"
+      );
+    } else {
       findFile = new RegExp(escapeRegex(attName) + "\\.(sig|asc)$");
     }
 
     for (let i in attachmentList) {
-      if ((i != index) &&
-        (this.getAttachmentName(attachmentList[i]).toLowerCase().search(findFile) === 0))
+      if (
+        i != index &&
+        this.getAttachmentName(attachmentList[i])
+          .toLowerCase()
+          .search(findFile) === 0
+      ) {
         signed = true;
+      }
     }
 
     return signed;
   },
 
   /**
    * Get the name of an attachment from the attachment object
    */
-  getAttachmentName: function(attachment) {
+  getAttachmentName(attachment) {
     return attachment.name;
   },
 
-
   /**
    * Escape text such that it can be used as HTML text
    */
-  escapeTextForHTML: function(text, hyperlink) {
+  escapeTextForHTML(text, hyperlink) {
     // Escape special characters
-    if (text.indexOf("&") > -1)
+    if (text.indexOf("&") > -1) {
       text = text.replace(/&/g, "&amp;");
+    }
 
-    if (text.indexOf("<") > -1)
+    if (text.indexOf("<") > -1) {
       text = text.replace(/</g, "&lt;");
+    }
 
-    if (text.indexOf(">") > -1)
+    if (text.indexOf(">") > -1) {
       text = text.replace(/>/g, "&gt;");
+    }
 
-    if (text.indexOf("\"") > -1)
+    if (text.indexOf('"') > -1) {
       text = text.replace(/"/g, "&quot;");
+    }
 
-    if (!hyperlink)
+    if (!hyperlink) {
       return text;
+    }
 
     // Hyperlink email addresses (we accept at most 1024 characters before and after the @)
-    var addrs = text.match(/\b[A-Za-z0-9_+.-]{1,1024}@[A-Za-z0-9.-]{1,1024}\b/g);
+    var addrs = text.match(
+      /\b[A-Za-z0-9_+.-]{1,1024}@[A-Za-z0-9.-]{1,1024}\b/g
+    );
 
     var newText, offset, loc;
     if (addrs && addrs.length) {
       newText = "";
       offset = 0;
 
       for (var j = 0; j < addrs.length; j++) {
         var addr = addrs[j];
 
         loc = text.indexOf(addr, offset);
-        if (loc < offset)
+        if (loc < offset) {
           break;
+        }
 
-        if (loc > offset)
+        if (loc > offset) {
           newText += text.substr(offset, loc - offset);
+        }
 
         // Strip any period off the end of address
         addr = addr.replace(/[.]$/, "");
 
-        if (!addr.length)
+        if (!addr.length) {
           continue;
+        }
 
-        newText += "<a href=\"mailto:" + addr + "\">" + addr + "</a>";
+        newText += '<a href="mailto:' + addr + '">' + addr + "</a>";
 
         offset = loc + addr.length;
       }
 
       newText += text.substr(offset, text.length - offset);
 
       text = newText;
     }
@@ -177,30 +206,33 @@ var EnigmailMsgRead = {
     if (urls && urls.length) {
       newText = "";
       offset = 0;
 
       for (var k = 0; k < urls.length; k++) {
         var url = urls[k];
 
         loc = text.indexOf(url, offset);
-        if (loc < offset)
+        if (loc < offset) {
           break;
+        }
 
-        if (loc > offset)
+        if (loc > offset) {
           newText += text.substr(offset, loc - offset);
+        }
 
         // Strip delimiters off the end of URL
         url = url.replace(/\s$/, "");
         url = url.replace(/([),.']|&gt;|&quot;)$/, "");
 
-        if (!url.length)
+        if (!url.length) {
           continue;
+        }
 
-        newText += "<a href=\"" + url + "\">" + url + "</a>";
+        newText += '<a href="' + url + '">' + url + "</a>";
 
         offset = loc + url.length;
       }
 
       newText += text.substr(offset, text.length - offset);
 
       text = newText;
     }
@@ -211,64 +243,68 @@ var EnigmailMsgRead = {
   /**
    * Match the key to the sender's from address
    *
    * @param {String}  keyId:    signing key ID
    * @param {String}  fromAddr: sender's email address
    *
    * @return Promise<String>: matching email address
    */
-  matchUidToSender: function(keyId, fromAddr) {
-    if ((!fromAddr) || !keyId) {
+  matchUidToSender(keyId, fromAddr) {
+    if (!fromAddr || !keyId) {
       return null;
     }
 
     try {
       fromAddr = EnigmailFuncs.stripEmail(fromAddr).toLowerCase();
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     let keyObj = EnigmailKeyRing.getKeyById(keyId);
-    if (!keyObj) return null;
+    if (!keyObj) {
+      return null;
+    }
 
     let userIdList = keyObj.userIds;
 
     try {
       for (let i = 0; i < userIdList.length; i++) {
-        if (fromAddr == EnigmailFuncs.stripEmail(userIdList[i].userId).toLowerCase()) {
+        if (
+          fromAddr ==
+          EnigmailFuncs.stripEmail(userIdList[i].userId).toLowerCase()
+        ) {
           return EnigmailFuncs.stripEmail(userIdList[i].userId);
         }
       }
 
       // // uid not found, try Autocrypt keystore
       // let acList = await EnigmailAutocrypt.getOpenPGPKeyForEmail([fromAddr]);
       // for (let i = 0; i < acList.length; i++) {
       //   if (acList[i].fpr == keyObj.fpr) {
       //     return fromAddr;
       //   }
       // }
-    }
-    catch (ex) {}
+    } catch (ex) {}
     return null;
   },
 
-  searchQuotedPgp: function(node) {
-    if (node.nodeName.toLowerCase() === "blockquote" &&
-      node.textContent.indexOf("-----BEGIN PGP ") >= 0) {
+  searchQuotedPgp(node) {
+    if (
+      node.nodeName.toLowerCase() === "blockquote" &&
+      node.textContent.includes("-----BEGIN PGP ")
+    ) {
       return true;
     }
 
     if (node.firstChild && this.searchQuotedPgp(node.firstChild)) {
       return true;
     }
 
     if (node.nextSibling && this.searchQuotedPgp(node.nextSibling)) {
       return true;
     }
 
     return false;
   },
 
-  trimAllLines: function(txt) {
-    return txt.replace(/^[ \t]+/mg, "");
-  }
-
+  trimAllLines(txt) {
+    return txt.replace(/^[ \t]+/gm, "");
+  },
 };
deleted file mode 100644
--- a/mail/extensions/openpgp/content/modules/openpgp.jsm
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * This Source Code Form is licensed under the GNU LGPL 3.0 license.
- *
- */
-
-"use strict";
-
-/**
- * This code is taken from openpgp.js
- *
- * Do OpenPGP packet parsing
- */
-
-/* eslint no-invalid-this: 0 */
-
-var EXPORTED_SYMBOLS = ["EnigmailOpenPGP"];
-
-var crc_table = [0x00000000, 0x00864cfb, 0x018ad50d, 0x010c99f6, 0x0393e6e1, 0x0315aa1a, 0x021933ec, 0x029f7f17, 0x07a18139, 0x0727cdc2, 0x062b5434, 0x06ad18cf, 0x043267d8, 0x04b42b23,
-  0x05b8b2d5, 0x053efe2e, 0x0fc54e89, 0x0f430272, 0x0e4f9b84, 0x0ec9d77f, 0x0c56a868, 0x0cd0e493, 0x0ddc7d65, 0x0d5a319e, 0x0864cfb0, 0x08e2834b, 0x09ee1abd, 0x09685646, 0x0bf72951,
-  0x0b7165aa, 0x0a7dfc5c, 0x0afbb0a7, 0x1f0cd1e9, 0x1f8a9d12, 0x1e8604e4, 0x1e00481f, 0x1c9f3708, 0x1c197bf3, 0x1d15e205, 0x1d93aefe, 0x18ad50d0, 0x182b1c2b, 0x192785dd, 0x19a1c926,
-  0x1b3eb631, 0x1bb8faca, 0x1ab4633c, 0x1a322fc7, 0x10c99f60, 0x104fd39b, 0x11434a6d, 0x11c50696, 0x135a7981, 0x13dc357a, 0x12d0ac8c, 0x1256e077, 0x17681e59, 0x17ee52a2, 0x16e2cb54,
-  0x166487af, 0x14fbf8b8, 0x147db443, 0x15712db5, 0x15f7614e, 0x3e19a3d2, 0x3e9fef29, 0x3f9376df, 0x3f153a24, 0x3d8a4533, 0x3d0c09c8, 0x3c00903e, 0x3c86dcc5, 0x39b822eb, 0x393e6e10,
-  0x3832f7e6, 0x38b4bb1d, 0x3a2bc40a, 0x3aad88f1, 0x3ba11107, 0x3b275dfc, 0x31dced5b, 0x315aa1a0, 0x30563856, 0x30d074ad, 0x324f0bba, 0x32c94741, 0x33c5deb7, 0x3343924c, 0x367d6c62,
-  0x36fb2099, 0x37f7b96f, 0x3771f594, 0x35ee8a83, 0x3568c678, 0x34645f8e, 0x34e21375, 0x2115723b, 0x21933ec0, 0x209fa736, 0x2019ebcd, 0x228694da, 0x2200d821, 0x230c41d7, 0x238a0d2c,
-  0x26b4f302, 0x2632bff9, 0x273e260f, 0x27b86af4, 0x252715e3, 0x25a15918, 0x24adc0ee, 0x242b8c15, 0x2ed03cb2, 0x2e567049, 0x2f5ae9bf, 0x2fdca544, 0x2d43da53, 0x2dc596a8, 0x2cc90f5e,
-  0x2c4f43a5, 0x2971bd8b, 0x29f7f170, 0x28fb6886, 0x287d247d, 0x2ae25b6a, 0x2a641791, 0x2b688e67, 0x2beec29c, 0x7c3347a4, 0x7cb50b5f, 0x7db992a9, 0x7d3fde52, 0x7fa0a145, 0x7f26edbe,
-  0x7e2a7448, 0x7eac38b3, 0x7b92c69d, 0x7b148a66, 0x7a181390, 0x7a9e5f6b, 0x7801207c, 0x78876c87, 0x798bf571, 0x790db98a, 0x73f6092d, 0x737045d6, 0x727cdc20, 0x72fa90db, 0x7065efcc,
-  0x70e3a337, 0x71ef3ac1, 0x7169763a, 0x74578814, 0x74d1c4ef, 0x75dd5d19, 0x755b11e2, 0x77c46ef5, 0x7742220e, 0x764ebbf8, 0x76c8f703, 0x633f964d, 0x63b9dab6, 0x62b54340, 0x62330fbb,
-  0x60ac70ac, 0x602a3c57, 0x6126a5a1, 0x61a0e95a, 0x649e1774, 0x64185b8f, 0x6514c279, 0x65928e82, 0x670df195, 0x678bbd6e, 0x66872498, 0x66016863, 0x6cfad8c4, 0x6c7c943f, 0x6d700dc9,
-  0x6df64132, 0x6f693e25, 0x6fef72de, 0x6ee3eb28, 0x6e65a7d3, 0x6b5b59fd, 0x6bdd1506, 0x6ad18cf0, 0x6a57c00b, 0x68c8bf1c, 0x684ef3e7, 0x69426a11, 0x69c426ea, 0x422ae476, 0x42aca88d,
-  0x43a0317b, 0x43267d80, 0x41b90297, 0x413f4e6c, 0x4033d79a, 0x40b59b61, 0x458b654f, 0x450d29b4, 0x4401b042, 0x4487fcb9, 0x461883ae, 0x469ecf55, 0x479256a3, 0x47141a58, 0x4defaaff,
-  0x4d69e604, 0x4c657ff2, 0x4ce33309, 0x4e7c4c1e, 0x4efa00e5, 0x4ff69913, 0x4f70d5e8, 0x4a4e2bc6, 0x4ac8673d, 0x4bc4fecb, 0x4b42b230, 0x49ddcd27, 0x495b81dc, 0x4857182a, 0x48d154d1,
-  0x5d26359f, 0x5da07964, 0x5cace092, 0x5c2aac69, 0x5eb5d37e, 0x5e339f85, 0x5f3f0673, 0x5fb94a88, 0x5a87b4a6, 0x5a01f85d, 0x5b0d61ab, 0x5b8b2d50, 0x59145247, 0x59921ebc, 0x589e874a,
-  0x5818cbb1, 0x52e37b16, 0x526537ed, 0x5369ae1b, 0x53efe2e0, 0x51709df7, 0x51f6d10c, 0x50fa48fa, 0x507c0401, 0x5542fa2f, 0x55c4b6d4, 0x54c82f22, 0x544e63d9, 0x56d11cce, 0x56575035,
-  0x575bc9c3, 0x57dd8538
-];
-
-function initialize() {
-  const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
-  EnigmailLog.DEBUG("openpgp.jsm: initialize()\n");
-
-}
-
-var EnigmailOpenPGP = {
-  get openpgp() {
-    if (!gOpenPGPLib) {
-      initialize();
-    }
-
-    return gOpenPGPLib;
-  },
-
-  armor: {
-    multipart_section: 0,
-    multipart_last: 1,
-    signed: 2,
-    message: 3,
-    public_key: 4,
-    private_key: 5,
-    signature: 6
-  },
-
-
-  enigmailFuncs: {
-
-    /**
-     * Convert a string to an Uint8Array
-     *
-     * @param  str: String with binary data
-     * @return Uint8Array
-     */
-    str2Uint8Array: function(str) {
-      var buf = new ArrayBuffer(str.length);
-      var bufView = new Uint8Array(buf);
-      for (var i = 0, strLen = str.length; i < strLen; i++) {
-        bufView[i] = str.charCodeAt(i);
-      }
-      return bufView;
-    },
-
-    /**
-     * Create CRC24 checksum
-     *
-     * @param input: Uint8Array of input data
-     *
-     * @return Number
-     */
-    createcrc24: function(input) {
-      var crc = 0xB704CE;
-      var index = 0;
-
-      while (input.length - index > 16) {
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 1]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 2]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 3]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 4]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 5]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 6]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 7]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 8]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 9]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 10]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 11]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 12]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 13]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 14]) & 0xff];
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index + 15]) & 0xff];
-        index += 16;
-      }
-
-      for (var j = index; j < input.length; j++) {
-        crc = crc << 8 ^ crc_table[(crc >> 16 ^ input[index++]) & 0xff];
-      }
-      return crc & 0xffffff;
-    },
-
-    /**
-     * Create an ASCII armored string from binary data. The message data is NOT
-     * checked for correctness, only the CRC is added at the end.
-     *
-     * @param msgType: Number - type of OpenPGP message to create (ARMOR Enum)
-     * @param str:     String - binary OpenPGP message
-     *
-     * @return String: ASCII armored OpenPGP message
-     */
-    bytesToArmor: function(msgType, str) {
-
-      const ARMOR_TYPE = EnigmailOpenPGP.armor;
-
-      let hdr = "";
-      switch (msgType) {
-        case ARMOR_TYPE.signed:
-        case ARMOR_TYPE.message:
-          hdr = "MESSAGE";
-          break;
-        case ARMOR_TYPE.public_key:
-          hdr = "PUBLIC KEY BLOCK";
-          break;
-        case ARMOR_TYPE.private_key:
-          hdr = "PRIVATE KEY BLOCK";
-          break;
-        case ARMOR_TYPE.signature:
-          hdr = "SIGNATURE";
-          break;
-      }
-
-      let crc = EnigmailOpenPGP.enigmailFuncs.createcrc24(EnigmailOpenPGP.enigmailFuncs.str2Uint8Array(str));
-      let crcAsc = String.fromCharCode(crc >> 16) + String.fromCharCode(crc >> 8 & 0xFF) + String.fromCharCode(crc & 0xFF);
-
-      let s = "-----BEGIN PGP " + hdr + "-----\n\n" +
-        btoa(str).replace(/(.{72})/g, "$1\n") + "\n" +
-        "=" + btoa(crcAsc) + "\n" +
-        "-----END PGP " + hdr + "-----\n";
-
-      return s;
-    }
-  }
-};
--- a/mail/extensions/openpgp/content/modules/os.jsm
+++ b/mail/extensions/openpgp/content/modules/os.jsm
@@ -3,23 +3,24 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailOS"];
 
-const XPCOM_APPINFO = "@mozilla.org/xre/app-info;1";
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 let operatingSystem = null;
 
 function getOS() {
   if (operatingSystem === null) {
-    operatingSystem = Cc[XPCOM_APPINFO].getService(Ci.nsIXULRuntime).OS;
+    operatingSystem = Services.appinfo.OS;
   }
   return operatingSystem;
 }
 
 function isDosLike() {
   return getOS() === "WINNT" || getOS() === "OS2";
 }
 
@@ -32,17 +33,17 @@ function isWin32() {
 }
 
 var EnigmailOS = {
   /*
    * getOS uses the Mozilla nsIXULRuntime Component to retrieve the OS Target
    *
    * @return   String    - OS Identifier
    */
-  getOS: getOS,
+  getOS,
 
   /**
    * isDosLike identifies whether the host computer is MS-DOS based
    *
    * @return    Boolean   - True if local host is MS-DOS based. False otherwise.
    */
   isDosLike: isDosLike(),
 
@@ -64,31 +65,31 @@ var EnigmailOS = {
    * get a Windows registry value (string)
    *
    * @param  keyPath String - the path of the registry (e.g. Software\\GNU\\GnuPG)
    * @param  keyName String - the name of the key to get (e.g. InstallDir)
    * @param  rootKey Number - HKLM, HKCU, etc. (according to constants in nsIWindowsRegKey)
    *
    * @return String - the found registry value (or empty string if not found)
    */
-  getWinRegistryString: function(keyPath, keyName, rootKey) {
-    const registry = Cc["@mozilla.org/windows-registry-key;1"].createInstance(Ci.nsIWindowsRegKey);
+  getWinRegistryString(keyPath, keyName, rootKey) {
+    const registry = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
+      Ci.nsIWindowsRegKey
+    );
 
     let retval = "";
     try {
       registry.open(rootKey, keyPath, registry.ACCESS_READ);
       retval = registry.readStringValue(keyName);
       registry.close();
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     return retval;
   },
 
-  getNullFile: function() {
+  getNullFile() {
     if (this.isDosLike) {
       return "NUL";
     }
-    else {
-      return "/dev/null";
-    }
-  }
+
+    return "/dev/null";
+  },
 };
--- a/mail/extensions/openpgp/content/modules/passwordCheck.jsm
+++ b/mail/extensions/openpgp/content/modules/passwordCheck.jsm
@@ -11,190 +11,190 @@ var EnigmailPasswordCheck = {
   /**
    *  Check password quality
    *
    *  password: String: the password to evaluate
    *
    *  return: object: valid:   Boolean - is password valid or not
    *                  complexity: Number  - complexity of password (values between 0 and 100)
    */
-  checkQuality: function(password) {
+  checkQuality(password) {
     return evaluateSecurity(password);
-  }
+  },
 };
 
 /*********
   Helper functions and variables
 */
 
-
 const COMPLEXIFY_BANLIST =
-  '123456|password|12345678|1234|pussy|12345|dragon|qwerty|696969|mustang|letmein|baseball|master|michael|football|shadow|monkey|abc123|pass|fuckme|6969|jordan|harley|ranger|iwantu|jennifer|hunter|fuck|2000|test|batman|trustno1|thomas|tigger|robert|access|love|buster|1234567|soccer|hockey|killer|george|sexy|andrew|charlie|superman|asshole|fuckyou|dallas|jessica|panties|pepper|1111|austin|william|daniel|golfer|summer|heather|hammer|yankees|joshua|maggie|biteme|enter|ashley|thunder|cowboy|silver|richard|fucker|orange|merlin|michelle|corvette|bigdog|cheese|matthew|121212|patrick|martin|freedom|ginger|blowjob|nicole|sparky|yellow|camaro|secret|dick|falcon|taylor|111111|131313|123123|bitch|hello|scooter|please|porsche|guitar|chelsea|black|diamond|nascar|jackson|cameron|654321|computer|amanda|wizard|xxxxxxxx|money|phoenix|mickey|bailey|knight|iceman|tigers|purple|andrea|horny|dakota|aaaaaa|player|sunshine|morgan|starwars|boomer|cowboys|edward|charles|girls|booboo|coffee|xxxxxx|bulldog|ncc1701|rabbit|peanut|john|johnny|gandalf|spanky|winter|brandy|compaq|carlos|tennis|james|mike|brandon|fender|anthony|blowme|ferrari|cookie|chicken|maverick|chicago|joseph|diablo|sexsex|hardcore|666666|willie|welcome|chris|panther|yamaha|justin|banana|driver|marine|angels|fishing|david|maddog|hooters|wilson|butthead|dennis|fucking|captain|bigdick|chester|smokey|xavier|steven|viking|snoopy|blue|eagles|winner|samantha|house|miller|flower|jack|firebird|butter|united|turtle|steelers|tiffany|zxcvbn|tomcat|golf|bond007|bear|tiger|doctor|gateway|gators|angel|junior|thx1138|porno|badboy|debbie|spider|melissa|booger|1212|flyers|fish|porn|matrix|teens|scooby|jason|walter|cumshot|boston|braves|yankee|lover|barney|victor|tucker|princess|mercedes|5150|doggie|' +
-  'zzzzzz|gunner|horney|bubba|2112|fred|johnson|xxxxx|tits|member|boobs|donald|bigdaddy|bronco|penis|voyager|rangers|birdie|trouble|white|topgun|bigtits|bitches|green|super|qazwsx|magic|lakers|rachel|slayer|scott|2222|asdf|video|london|7777|marlboro|srinivas|internet|action|carter|jasper|monster|teresa|jeremy|11111111|bill|crystal|peter|pussies|cock|beer|rocket|theman|oliver|prince|beach|amateur|7777777|muffin|redsox|star|testing|shannon|murphy|frank|hannah|dave|eagle1|11111|mother|nathan|raiders|steve|forever|angela|viper|ou812|jake|lovers|suckit|gregory|buddy|whatever|young|nicholas|lucky|helpme|jackie|monica|midnight|college|baby|cunt|brian|mark|startrek|sierra|leather|232323|4444|beavis|bigcock|happy|sophie|ladies|naughty|giants|booty|blonde|fucked|golden|0|fire|sandra|pookie|packers|einstein|dolphins|chevy|winston|warrior|sammy|slut|8675309|zxcvbnm|nipples|power|victoria|asdfgh|vagina|toyota|travis|hotdog|paris|rock|xxxx|extreme|redskins|erotic|dirty|ford|freddy|arsenal|access14|wolf|nipple|iloveyou|alex|florida|eric|legend|movie|success|rosebud|jaguar|great|cool|cooper|1313|scorpio|mountain|madison|987654|brazil|lauren|japan|naked|squirt|stars|apple|alexis|aaaa|bonnie|peaches|jasmine|kevin|matt|qwertyui|danielle|beaver|4321|4128|runner|swimming|dolphin|gordon|casper|stupid|shit|saturn|gemini|apples|august|3333|canada|blazer|cumming|hunting|kitty|rainbow|112233|arthur|cream|calvin|shaved|surfer|samson|kelly|paul|mine|king|racing|5555|eagle|hentai|newyork|little|redwings|smith|sticky|cocacola|animal|broncos|private|skippy|marvin|blondes|enjoy|girl|apollo|parker|qwert|time|sydney|women|voodoo|magnum|juice|abgrtyu|777777|dreams|maxwell|music|rush2112|russia|scorpion|rebecca|tester|mistress|phantom|billy|6666|albert|111111|11111111|112233|' +
-  '121212|123123|123456|1234567|12345678|131313|232323|654321|666666|696969|777777|7777777|8675309|987654|abcdef|password1|password12|password123|twitter'.split('|');
+  "123456|password|12345678|1234|pussy|12345|dragon|qwerty|696969|mustang|letmein|baseball|master|michael|football|shadow|monkey|abc123|pass|fuckme|6969|jordan|harley|ranger|iwantu|jennifer|hunter|fuck|2000|test|batman|trustno1|thomas|tigger|robert|access|love|buster|1234567|soccer|hockey|killer|george|sexy|andrew|charlie|superman|asshole|fuckyou|dallas|jessica|panties|pepper|1111|austin|william|daniel|golfer|summer|heather|hammer|yankees|joshua|maggie|biteme|enter|ashley|thunder|cowboy|silver|richard|fucker|orange|merlin|michelle|corvette|bigdog|cheese|matthew|121212|patrick|martin|freedom|ginger|blowjob|nicole|sparky|yellow|camaro|secret|dick|falcon|taylor|111111|131313|123123|bitch|hello|scooter|please|porsche|guitar|chelsea|black|diamond|nascar|jackson|cameron|654321|computer|amanda|wizard|xxxxxxxx|money|phoenix|mickey|bailey|knight|iceman|tigers|purple|andrea|horny|dakota|aaaaaa|player|sunshine|morgan|starwars|boomer|cowboys|edward|charles|girls|booboo|coffee|xxxxxx|bulldog|ncc1701|rabbit|peanut|john|johnny|gandalf|spanky|winter|brandy|compaq|carlos|tennis|james|mike|brandon|fender|anthony|blowme|ferrari|cookie|chicken|maverick|chicago|joseph|diablo|sexsex|hardcore|666666|willie|welcome|chris|panther|yamaha|justin|banana|driver|marine|angels|fishing|david|maddog|hooters|wilson|butthead|dennis|fucking|captain|bigdick|chester|smokey|xavier|steven|viking|snoopy|blue|eagles|winner|samantha|house|miller|flower|jack|firebird|butter|united|turtle|steelers|tiffany|zxcvbn|tomcat|golf|bond007|bear|tiger|doctor|gateway|gators|angel|junior|thx1138|porno|badboy|debbie|spider|melissa|booger|1212|flyers|fish|porn|matrix|teens|scooby|jason|walter|cumshot|boston|braves|yankee|lover|barney|victor|tucker|princess|mercedes|5150|doggie|" +
+  "zzzzzz|gunner|horney|bubba|2112|fred|johnson|xxxxx|tits|member|boobs|donald|bigdaddy|bronco|penis|voyager|rangers|birdie|trouble|white|topgun|bigtits|bitches|green|super|qazwsx|magic|lakers|rachel|slayer|scott|2222|asdf|video|london|7777|marlboro|srinivas|internet|action|carter|jasper|monster|teresa|jeremy|11111111|bill|crystal|peter|pussies|cock|beer|rocket|theman|oliver|prince|beach|amateur|7777777|muffin|redsox|star|testing|shannon|murphy|frank|hannah|dave|eagle1|11111|mother|nathan|raiders|steve|forever|angela|viper|ou812|jake|lovers|suckit|gregory|buddy|whatever|young|nicholas|lucky|helpme|jackie|monica|midnight|college|baby|cunt|brian|mark|startrek|sierra|leather|232323|4444|beavis|bigcock|happy|sophie|ladies|naughty|giants|booty|blonde|fucked|golden|0|fire|sandra|pookie|packers|einstein|dolphins|chevy|winston|warrior|sammy|slut|8675309|zxcvbnm|nipples|power|victoria|asdfgh|vagina|toyota|travis|hotdog|paris|rock|xxxx|extreme|redskins|erotic|dirty|ford|freddy|arsenal|access14|wolf|nipple|iloveyou|alex|florida|eric|legend|movie|success|rosebud|jaguar|great|cool|cooper|1313|scorpio|mountain|madison|987654|brazil|lauren|japan|naked|squirt|stars|apple|alexis|aaaa|bonnie|peaches|jasmine|kevin|matt|qwertyui|danielle|beaver|4321|4128|runner|swimming|dolphin|gordon|casper|stupid|shit|saturn|gemini|apples|august|3333|canada|blazer|cumming|hunting|kitty|rainbow|112233|arthur|cream|calvin|shaved|surfer|samson|kelly|paul|mine|king|racing|5555|eagle|hentai|newyork|little|redwings|smith|sticky|cocacola|animal|broncos|private|skippy|marvin|blondes|enjoy|girl|apollo|parker|qwert|time|sydney|women|voodoo|magnum|juice|abgrtyu|777777|dreams|maxwell|music|rush2112|russia|scorpion|rebecca|tester|mistress|phantom|billy|6666|albert|111111|11111111|112233|" +
+  "121212|123123|123456|1234567|12345678|131313|232323|654321|666666|696969|777777|7777777|8675309|987654|abcdef|password1|password12|password123|twitter".split(
+    "|"
+  );
 
 const options = {
   minimumChars: 8,
   strengthScaleFactor: 1,
   bannedPasswords: COMPLEXIFY_BANLIST,
-  banMode: 'strict' // (strict|loose)
+  banMode: "strict", // (strict|loose)
 };
 
 const MIN_COMPLEXITY = 30; // 8 chars with Upper, Lower and Number
 //var MAX_COMPLEXITY = 120; //  25 chars, all charsets
 const MAX_COMPLEXITY = 60;
 
 const CHARSETS = [
   // Commonly Used
   ////////////////////
   [0x0020, 0x0020], // Space
   [0x0030, 0x0039], // Numbers
-  [0x0041, 0x005A], // Uppercase
-  [0x0061, 0x007A], // Lowercase
-  [0x0021, 0x002F], // Punctuation
-  [0x003A, 0x0040], // Punctuation
-  [0x005B, 0x0060], // Punctuation
-  [0x007B, 0x007E], // Punctuation
+  [0x0041, 0x005a], // Uppercase
+  [0x0061, 0x007a], // Lowercase
+  [0x0021, 0x002f], // Punctuation
+  [0x003a, 0x0040], // Punctuation
+  [0x005b, 0x0060], // Punctuation
+  [0x007b, 0x007e], // Punctuation
   // Everything Else
   ////////////////////
-  [0x0080, 0x00FF], // Latin-1 Supplement
-  [0x0100, 0x017F], // Latin Extended-A
-  [0x0180, 0x024F], // Latin Extended-B
-  [0x0250, 0x02AF], // IPA Extensions
-  [0x02B0, 0x02FF], // Spacing Modifier Letters
-  [0x0300, 0x036F], // Combining Diacritical Marks
-  [0x0370, 0x03FF], // Greek
-  [0x0400, 0x04FF], // Cyrillic
-  [0x0530, 0x058F], // Armenian
-  [0x0590, 0x05FF], // Hebrew
-  [0x0600, 0x06FF], // Arabic
-  [0x0700, 0x074F], // Syriac
-  [0x0780, 0x07BF], // Thaana
-  [0x0900, 0x097F], // Devanagari
-  [0x0980, 0x09FF], // Bengali
-  [0x0A00, 0x0A7F], // Gurmukhi
-  [0x0A80, 0x0AFF], // Gujarati
-  [0x0B00, 0x0B7F], // Oriya
-  [0x0B80, 0x0BFF], // Tamil
-  [0x0C00, 0x0C7F], // Telugu
-  [0x0C80, 0x0CFF], // Kannada
-  [0x0D00, 0x0D7F], // Malayalam
-  [0x0D80, 0x0DFF], // Sinhala
-  [0x0E00, 0x0E7F], // Thai
-  [0x0E80, 0x0EFF], // Lao
-  [0x0F00, 0x0FFF], // Tibetan
-  [0x1000, 0x109F], // Myanmar
-  [0x10A0, 0x10FF], // Georgian
-  [0x1100, 0x11FF], // Hangul Jamo
-  [0x1200, 0x137F], // Ethiopic
-  [0x13A0, 0x13FF], // Cherokee
-  [0x1400, 0x167F], // Unified Canadian Aboriginal Syllabics
-  [0x1680, 0x169F], // Ogham
-  [0x16A0, 0x16FF], // Runic
-  [0x1780, 0x17FF], // Khmer
-  [0x1800, 0x18AF], // Mongolian
-  [0x1E00, 0x1EFF], // Latin Extended Additional
-  [0x1F00, 0x1FFF], // Greek Extended
-  [0x2000, 0x206F], // General Punctuation
-  [0x2070, 0x209F], // Superscripts and Subscripts
-  [0x20A0, 0x20CF], // Currency Symbols
-  [0x20D0, 0x20FF], // Combining Marks for Symbols
-  [0x2100, 0x214F], // Letterlike Symbols
-  [0x2150, 0x218F], // Number Forms
-  [0x2190, 0x21FF], // Arrows
-  [0x2200, 0x22FF], // Mathematical Operators
-  [0x2300, 0x23FF], // Miscellaneous Technical
-  [0x2400, 0x243F], // Control Pictures
-  [0x2440, 0x245F], // Optical Character Recognition
-  [0x2460, 0x24FF], // Enclosed Alphanumerics
-  [0x2500, 0x257F], // Box Drawing
-  [0x2580, 0x259F], // Block Elements
-  [0x25A0, 0x25FF], // Geometric Shapes
-  [0x2600, 0x26FF], // Miscellaneous Symbols
-  [0x2700, 0x27BF], // Dingbats
-  [0x2800, 0x28FF], // Braille Patterns
-  [0x2E80, 0x2EFF], // CJK Radicals Supplement
-  [0x2F00, 0x2FDF], // Kangxi Radicals
-  [0x2FF0, 0x2FFF], // Ideographic Description Characters
-  [0x3000, 0x303F], // CJK Symbols and Punctuation
-  [0x3040, 0x309F], // Hiragana
-  [0x30A0, 0x30FF], // Katakana
-  [0x3100, 0x312F], // Bopomofo
-  [0x3130, 0x318F], // Hangul Compatibility Jamo
-  [0x3190, 0x319F], // Kanbun
-  [0x31A0, 0x31BF], // Bopomofo Extended
-  [0x3200, 0x32FF], // Enclosed CJK Letters and Months
-  [0x3300, 0x33FF], // CJK Compatibility
-  [0x3400, 0x4DB5], // CJK Unified Ideographs Extension A
-  [0x4E00, 0x9FFF], // CJK Unified Ideographs
-  [0xA000, 0xA48F], // Yi Syllables
-  [0xA490, 0xA4CF], // Yi Radicals
-  [0xAC00, 0xD7A3], // Hangul Syllables
-  [0xD800, 0xDB7F], // High Surrogates
-  [0xDB80, 0xDBFF], // High Private Use Surrogates
-  [0xDC00, 0xDFFF], // Low Surrogates
-  [0xE000, 0xF8FF], // Private Use
-  [0xF900, 0xFAFF], // CJK Compatibility Ideographs
-  [0xFB00, 0xFB4F], // Alphabetic Presentation Forms
-  [0xFB50, 0xFDFF], // Arabic Presentation Forms-A
-  [0xFE20, 0xFE2F], // Combining Half Marks
-  [0xFE30, 0xFE4F], // CJK Compatibility Forms
-  [0xFE50, 0xFE6F], // Small Form Variants
-  [0xFE70, 0xFEFE], // Arabic Presentation Forms-B
-  [0xFEFF, 0xFEFF], // Specials
-  [0xFF00, 0xFFEF], // Halfwidth and Fullwidth Forms
-  [0xFFF0, 0xFFFD] // Specials
+  [0x0080, 0x00ff], // Latin-1 Supplement
+  [0x0100, 0x017f], // Latin Extended-A
+  [0x0180, 0x024f], // Latin Extended-B
+  [0x0250, 0x02af], // IPA Extensions
+  [0x02b0, 0x02ff], // Spacing Modifier Letters
+  [0x0300, 0x036f], // Combining Diacritical Marks
+  [0x0370, 0x03ff], // Greek
+  [0x0400, 0x04ff], // Cyrillic
+  [0x0530, 0x058f], // Armenian
+  [0x0590, 0x05ff], // Hebrew
+  [0x0600, 0x06ff], // Arabic
+  [0x0700, 0x074f], // Syriac
+  [0x0780, 0x07bf], // Thaana
+  [0x0900, 0x097f], // Devanagari
+  [0x0980, 0x09ff], // Bengali
+  [0x0a00, 0x0a7f], // Gurmukhi
+  [0x0a80, 0x0aff], // Gujarati
+  [0x0b00, 0x0b7f], // Oriya
+  [0x0b80, 0x0bff], // Tamil
+  [0x0c00, 0x0c7f], // Telugu
+  [0x0c80, 0x0cff], // Kannada
+  [0x0d00, 0x0d7f], // Malayalam
+  [0x0d80, 0x0dff], // Sinhala
+  [0x0e00, 0x0e7f], // Thai
+  [0x0e80, 0x0eff], // Lao
+  [0x0f00, 0x0fff], // Tibetan
+  [0x1000, 0x109f], // Myanmar
+  [0x10a0, 0x10ff], // Georgian
+  [0x1100, 0x11ff], // Hangul Jamo
+  [0x1200, 0x137f], // Ethiopic
+  [0x13a0, 0x13ff], // Cherokee
+  [0x1400, 0x167f], // Unified Canadian Aboriginal Syllabics
+  [0x1680, 0x169f], // Ogham
+  [0x16a0, 0x16ff], // Runic
+  [0x1780, 0x17ff], // Khmer
+  [0x1800, 0x18af], // Mongolian
+  [0x1e00, 0x1eff], // Latin Extended Additional
+  [0x1f00, 0x1fff], // Greek Extended
+  [0x2000, 0x206f], // General Punctuation
+  [0x2070, 0x209f], // Superscripts and Subscripts
+  [0x20a0, 0x20cf], // Currency Symbols
+  [0x20d0, 0x20ff], // Combining Marks for Symbols
+  [0x2100, 0x214f], // Letterlike Symbols
+  [0x2150, 0x218f], // Number Forms
+  [0x2190, 0x21ff], // Arrows
+  [0x2200, 0x22ff], // Mathematical Operators
+  [0x2300, 0x23ff], // Miscellaneous Technical
+  [0x2400, 0x243f], // Control Pictures
+  [0x2440, 0x245f], // Optical Character Recognition
+  [0x2460, 0x24ff], // Enclosed Alphanumerics
+  [0x2500, 0x257f], // Box Drawing
+  [0x2580, 0x259f], // Block Elements
+  [0x25a0, 0x25ff], // Geometric Shapes
+  [0x2600, 0x26ff], // Miscellaneous Symbols
+  [0x2700, 0x27bf], // Dingbats
+  [0x2800, 0x28ff], // Braille Patterns
+  [0x2e80, 0x2eff], // CJK Radicals Supplement
+  [0x2f00, 0x2fdf], // Kangxi Radicals
+  [0x2ff0, 0x2fff], // Ideographic Description Characters
+  [0x3000, 0x303f], // CJK Symbols and Punctuation
+  [0x3040, 0x309f], // Hiragana
+  [0x30a0, 0x30ff], // Katakana
+  [0x3100, 0x312f], // Bopomofo
+  [0x3130, 0x318f], // Hangul Compatibility Jamo
+  [0x3190, 0x319f], // Kanbun
+  [0x31a0, 0x31bf], // Bopomofo Extended
+  [0x3200, 0x32ff], // Enclosed CJK Letters and Months
+  [0x3300, 0x33ff], // CJK Compatibility
+  [0x3400, 0x4db5], // CJK Unified Ideographs Extension A
+  [0x4e00, 0x9fff], // CJK Unified Ideographs
+  [0xa000, 0xa48f], // Yi Syllables
+  [0xa490, 0xa4cf], // Yi Radicals
+  [0xac00, 0xd7a3], // Hangul Syllables
+  [0xd800, 0xdb7f], // High Surrogates
+  [0xdb80, 0xdbff], // High Private Use Surrogates
+  [0xdc00, 0xdfff], // Low Surrogates
+  [0xe000, 0xf8ff], // Private Use
+  [0xf900, 0xfaff], // CJK Compatibility Ideographs
+  [0xfb00, 0xfb4f], // Alphabetic Presentation Forms
+  [0xfb50, 0xfdff], // Arabic Presentation Forms-A
+  [0xfe20, 0xfe2f], // Combining Half Marks
+  [0xfe30, 0xfe4f], // CJK Compatibility Forms
+  [0xfe50, 0xfe6f], // Small Form Variants
+  [0xfe70, 0xfefe], // Arabic Presentation Forms-B
+  [0xfeff, 0xfeff], // Specials
+  [0xff00, 0xffef], // Halfwidth and Fullwidth Forms
+  [0xfff0, 0xfffd], // Specials
 ];
 
 function additionalComplexityForCharset(str, charset) {
   for (var i = str.length - 1; i >= 0; i--) {
     if (charset[0] <= str.charCodeAt(i) && str.charCodeAt(i) <= charset[1]) {
       return charset[1] - charset[0] + 1;
     }
   }
   return 0;
 }
 
 function inBanlist(str) {
-  if (options.banMode === 'strict') {
+  if (options.banMode === "strict") {
     for (var i = 0; i < options.bannedPasswords.length; i++) {
-      if (options.bannedPasswords[i].indexOf(str) !== -1) {
+      if (options.bannedPasswords[i].includes(str)) {
         return true;
       }
     }
     return false;
   }
-  else {
-    return (options.bannedPasswords.indexOf(str) > -1 ? true : false);
-  }
+
+  return options.bannedPasswords.indexOf(str) > -1;
 }
 
 function evaluateSecurity(password) {
   var complexity = 0,
     valid = false;
 
   // Reset complexity to 0 when banned password is found
   if (!inBanlist(password)) {
-
     // Add character complexity
     for (var i = CHARSETS.length - 1; i >= 0; i--) {
       complexity += additionalComplexityForCharset(password, CHARSETS[i]);
     }
-
-  }
-  else {
+  } else {
     complexity = 1;
   }
 
   // Use natural log to produce linear scale
-  complexity = Math.log(Math.pow(complexity, password.length)) * (1 / options.strengthScaleFactor);
+  complexity =
+    Math.log(Math.pow(complexity, password.length)) *
+    (1 / options.strengthScaleFactor);
 
-  valid = (complexity > MIN_COMPLEXITY && password.length >= options.minimumChars);
+  valid =
+    complexity > MIN_COMPLEXITY && password.length >= options.minimumChars;
 
   // Scale to percentage, so it can be used for a progress bar
   complexity = (complexity / MAX_COMPLEXITY) * 100;
-  complexity = (complexity > 100) ? 100 : complexity;
+  complexity = complexity > 100 ? 100 : complexity;
 
   return {
-    valid: valid,
-    complexity: complexity
+    valid,
+    complexity,
   };
 }
--- a/mail/extensions/openpgp/content/modules/persistentCrypto.jsm
+++ b/mail/extensions/openpgp/content/modules/persistentCrypto.jsm
@@ -1,57 +1,82 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
+"use strict";
 
-"use strict";
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 var EXPORTED_SYMBOLS = ["EnigmailPersistentCrypto"];
 
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const GlodaUtils = ChromeUtils.import("chrome://openpgp/content/modules/glodaUtils.jsm").GlodaUtils;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailArmor = ChromeUtils.import(
+  "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const GlodaUtils = ChromeUtils.import(
+  "chrome://openpgp/content/modules/glodaUtils.jsm"
+).GlodaUtils;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
 const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-const EnigmailEncryption = ChromeUtils.import("chrome://openpgp/content/modules/encryption.jsm").EnigmailEncryption;
+const EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+const EnigmailEncryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/encryption.jsm"
+).EnigmailEncryption;
 
-const getFixExchangeMsg = EnigmailLazy.loader("enigmail/fixExchangeMsg.jsm", "EnigmailFixExchangeMsg");
-const getDecryption = EnigmailLazy.loader("enigmail/decryption.jsm", "EnigmailDecryption");
+const getFixExchangeMsg = EnigmailLazy.loader(
+  "enigmail/fixExchangeMsg.jsm",
+  "EnigmailFixExchangeMsg"
+);
+const getDecryption = EnigmailLazy.loader(
+  "enigmail/decryption.jsm",
+  "EnigmailDecryption"
+);
 const getDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
 
-const STATUS_OK = 0;
-const STATUS_FAILURE = 1;
-const STATUS_NOT_REQUIRED = 2;
-
-const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
-
 /*
  *  Decrypt a message and copy it to a folder
  *
  * @param nsIMsgDBHdr hdr   Header of the message
  * @param String destFolder   Folder URI
  * @param Boolean move      If true the original message will be deleted
  *
  * @return a Promise that we do that
  */
 var EnigmailPersistentCrypto = {
-
   /***
    *  dispatchMessages
    *
    *  Because Thunderbird throws all messages at once at us thus we have to rate limit the dispatching
    *  of the message processing. Because there is only a negligible performance gain when dispatching
    *  several message at once we serialize to not overwhelm low power devices.
    *
    *  If targetFolder is null the message will be copied / moved in the same folder as the original
@@ -65,35 +90,46 @@ var EnigmailPersistentCrypto = {
    *   aMsgHdrs:     Array of nsIMsgDBHdr
    *   targetFolder: String; target folder URI or null
    *   copyListener: listener for async request (nsIMsgCopyServiceListener)
    *   move:         Boolean: type of action; true = "move" / false = "copy"
    *   targetKey:    KeyObject of target key if encryption is requested
    *
    **/
 
-  dispatchMessages: function(aMsgHdrs, targetFolder, copyListener, move, targetKey) {
+  dispatchMessages(aMsgHdrs, targetFolder, copyListener, move, targetKey) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: dispatchMessages()\n");
 
     let enigmailSvc = EnigmailCore.getService();
     if (copyListener && !enigmailSvc) {
       // could not initiate Enigmail - do nothing
       copyListener.OnStopCopy(0);
       return;
     }
 
     if (copyListener) {
       copyListener.OnStartCopy();
     }
-    let promise = EnigmailPersistentCrypto.cryptMessage(aMsgHdrs[0], targetFolder, move, targetKey);
+    let promise = EnigmailPersistentCrypto.cryptMessage(
+      aMsgHdrs[0],
+      targetFolder,
+      move,
+      targetKey
+    );
 
     let processNext = function(data) {
       aMsgHdrs.splice(0, 1);
       if (aMsgHdrs.length > 0) {
-        EnigmailPersistentCrypto.dispatchMessages(aMsgHdrs, targetFolder, copyListener, move, targetKey);
+        EnigmailPersistentCrypto.dispatchMessages(
+          aMsgHdrs,
+          targetFolder,
+          copyListener,
+          move,
+          targetKey
+        );
       } else {
         // last message was finished processing
         if (copyListener) {
           copyListener.OnStopCopy(0);
         }
         EnigmailLog.DEBUG("persistentCrypto.jsm: dispatchMessages - DONE\n");
       }
     };
@@ -112,52 +148,53 @@ var EnigmailPersistentCrypto = {
    *  encrypts a message to the target key afterwards.
    *
    *  Parameters
    *   hdr:        nsIMsgDBHdr of the message to encrypt
    *   destFolder: String; target folder URI
    *   move:       Boolean: type of action; true = "move" / false = "copy"
    *   targetKey:  KeyObject of target key if encryption is requested
    **/
-  cryptMessage: function(hdr, destFolder, move, targetKey) {
-    return new Promise(
-      function(resolve, reject) {
-        let msgUriSpec = hdr.folder.getUriForMsg(hdr);
-        let msgUrl = EnigmailCompat.getUrlFromUriSpec(msgUriSpec);
-
-        const crypt = new CryptMessageIntoFolder(destFolder, move, resolve, targetKey);
+  cryptMessage(hdr, destFolder, move, targetKey) {
+    return new Promise(function(resolve, reject) {
+      let msgUriSpec = hdr.folder.getUriForMsg(hdr);
+      let msgUrl = EnigmailCompat.getUrlFromUriSpec(msgUriSpec);
 
-        try {
-          EnigmailMime.getMimeTreeFromUrl(msgUrl, true,
-            function f_(mime) {
-              crypt.messageParseCallback(mime, hdr);
-            });
-        } catch (ex) {
-          reject("msgHdrsDeleteoMimeMessage failed: " + ex.toString());
-        }
-        return;
+      const crypt = new CryptMessageIntoFolder(
+        destFolder,
+        move,
+        resolve,
+        targetKey
+      );
+
+      try {
+        EnigmailMime.getMimeTreeFromUrl(msgUrl, true, function(mime) {
+          crypt.messageParseCallback(mime, hdr);
+        });
+      } catch (ex) {
+        reject("msgHdrsDeleteoMimeMessage failed: " + ex.toString());
       }
-    );
-  }
+    });
+  },
 };
 
 function CryptMessageIntoFolder(destFolder, move, resolve, targetKey) {
   this.destFolder = destFolder;
   this.move = move;
   this.resolve = resolve;
   this.targetKey = targetKey;
   this.messageDecrypted = false;
 
   this.mimeTree = null;
   this.decryptionTasks = [];
   this.subject = "";
 }
 
 CryptMessageIntoFolder.prototype = {
-  messageParseCallback: async function(mimeTree, msgHdr) {
+  async messageParseCallback(mimeTree, msgHdr) {
     this.mimeTree = mimeTree;
     this.hdr = msgHdr;
 
     if (mimeTree.headers.has("subject")) {
       this.subject = mimeTree.headers.get("subject");
     }
 
     await this.decryptMimeTree(mimeTree);
@@ -166,105 +203,109 @@ CryptMessageIntoFolder.prototype = {
 
     // Encrypt the message if a target key is given.
     if (this.targetKey) {
       msg = this.encryptToKey(mimeTree);
       if (!msg) {
         // do nothing (still better than destroying the message)
         this.resolve(true);
         return;
-      } else {
-        this.messageDecrypted = true;
       }
+      this.messageDecrypted = true;
     } else if (this.messageDecrypted) {
       msg = this.mimeToString(mimeTree, true);
     }
 
     if (this.messageDecrypted) {
       this.resolve(await this.storeMessage(msg));
-    } else
+    } else {
       this.resolve(true);
+    }
   },
 
-  encryptToKey: function(mimeTree) {
+  encryptToKey(mimeTree) {
     let exitCodeObj = {};
     let statusFlagsObj = {};
     let errorMsgObj = {};
     EnigmailLog.DEBUG("persistentCrypto.jsm: Encrypting message.\n");
 
-
     let inputMsg = this.mimeToString(mimeTree, false);
 
-
     let encmsg = "";
     try {
-      encmsg = EnigmailEncryption.encryptMessage(null,
+      encmsg = EnigmailEncryption.encryptMessage(
+        null,
         0,
         inputMsg,
         "0x" + this.targetKey.fpr,
         "0x" + this.targetKey.fpr,
         "",
         EnigmailConstants.SEND_ENCRYPTED | EnigmailConstants.SEND_ALWAYS_TRUST,
         exitCodeObj,
         statusFlagsObj,
         errorMsgObj
       );
     } catch (ex) {
-      EnigmailLog.DEBUG("persistentCrypto.jsm: Encryption failed: " + ex + "\n");
+      EnigmailLog.DEBUG(
+        "persistentCrypto.jsm: Encryption failed: " + ex + "\n"
+      );
       return null;
     }
 
     // Build the pgp-encrypted mime structure
     let msg = "";
 
     let rfc822Headers = []; // FIXME
 
     // First the original headers
     for (let header in rfc822Headers) {
-      if (header != "content-type" &&
+      if (
+        header != "content-type" &&
         header != "content-transfer-encoding" &&
-        header != "content-disposition") {
+        header != "content-disposition"
+      ) {
         msg += prettyPrintHeader(header, rfc822Headers[header]) + "\n";
       }
     }
     // Then multipart/encrypted ct
     let boundary = EnigmailMime.createBoundary();
     msg += "Content-Transfer-Encoding: 7Bit\n";
     msg += "Content-Type: multipart/encrypted; ";
-    msg += "boundary=\"" + boundary + "\"; protocol=\"application/pgp-encrypted\"\n\n";
+    msg +=
+      'boundary="' + boundary + '"; protocol="application/pgp-encrypted"\n\n';
     msg += "This is an OpenPGP/MIME encrypted message (RFC 4880 and 3156)\n";
 
     // pgp-encrypted part
     msg += "--" + boundary + "\n";
     msg += "Content-Type: application/pgp-encrypted\n";
     msg += "Content-Disposition: attachment\n";
     msg += "Content-Transfer-Encoding: 7Bit\n\n";
     msg += "Version: 1\n\n";
 
     // the octet stream
     msg += "--" + boundary + "\n";
-    msg += "Content-Type: application/octet-stream; name=\"encrypted.asc\"\n";
+    msg += 'Content-Type: application/octet-stream; name="encrypted.asc"\n';
     msg += "Content-Description: OpenPGP encrypted message\n";
-    msg += "Content-Disposition: inline; filename=\"encrypted.asc\"\n";
+    msg += 'Content-Disposition: inline; filename="encrypted.asc"\n';
     msg += "Content-Transfer-Encoding: 7Bit\n\n";
     msg += encmsg;
 
     // Bottom boundary
     msg += "\n--" + boundary + "--\n";
 
     // Fix up the line endings to be a proper dosish mail
-    msg = msg.replace(/\r/ig, "").replace(/\n/ig, "\r\n");
+    msg = msg.replace(/\r/gi, "").replace(/\n/gi, "\r\n");
 
     return msg;
   },
 
   /**
    *  Walk through the MIME message structure and decrypt the body if there is something to decrypt
    */
-  decryptMimeTree: async function(mimePart) {
+  async decryptMimeTree(mimePart) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: decryptMimeTree:\n");
 
     if (this.isBrokenByExchange(mimePart)) {
       this.fixExchangeMessage(mimePart);
     }
 
     if (this.isPgpMime(mimePart)) {
       this.decryptPGPMIME(mimePart);
@@ -286,86 +327,125 @@ CryptMessageIntoFolder.prototype = {
    * - multipart/mixed Container with
    *   - application/pgp-encrypted Attachment with name "PGPMIME Version Identification"
    *   - application/octet-stream Attachment with name "encrypted.asc" having the encrypted content in base64
    * - see:
    *   - https://doesnotexist-openpgp-integration.thunderbird/forum/viewtopic.php?f=4&t=425
    *   - https://sourceforge.net/p/enigmail/forum/support/thread/4add2b69/
    */
 
-  isBrokenByExchange: function(mime) {
+  isBrokenByExchange(mime) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: isBrokenByExchange:\n");
 
     try {
-      if (mime.subParts && mime.subParts.length === 3 &&
-        mime.fullContentType.toLowerCase().indexOf("multipart/mixed") >= 0 &&
+      if (
+        mime.subParts &&
+        mime.subParts.length === 3 &&
+        mime.fullContentType.toLowerCase().includes("multipart/mixed") &&
         mime.subParts[0].subParts.length === 0 &&
         mime.subParts[0].fullContentType.search(/multipart\/encrypted/i) < 0 &&
-        mime.subParts[0].fullContentType.toLowerCase().indexOf("text/plain") >= 0 &&
-        mime.subParts[1].fullContentType.toLowerCase().indexOf("application/pgp-encrypted") >= 0 &&
-        mime.subParts[1].fullContentType.toLowerCase().search(/multipart\/encrypted/i) < 0 &&
-        mime.subParts[1].fullContentType.toLowerCase().search(/PGPMIME Versions? Identification/i) >= 0 &&
-        mime.subParts[2].fullContentType.toLowerCase().indexOf("application/octet-stream") >= 0 &&
-        mime.subParts[2].fullContentType.toLowerCase().indexOf("encrypted.asc") >= 0) {
-
-        EnigmailLog.DEBUG("persistentCrypto.jsm: isBrokenByExchange: found message broken by MS-Exchange\n");
+        mime.subParts[0].fullContentType.toLowerCase().includes("text/plain") &&
+        mime.subParts[1].fullContentType
+          .toLowerCase()
+          .includes("application/pgp-encrypted") &&
+        mime.subParts[1].fullContentType
+          .toLowerCase()
+          .search(/multipart\/encrypted/i) < 0 &&
+        mime.subParts[1].fullContentType
+          .toLowerCase()
+          .search(/PGPMIME Versions? Identification/i) >= 0 &&
+        mime.subParts[2].fullContentType
+          .toLowerCase()
+          .includes("application/octet-stream") &&
+        mime.subParts[2].fullContentType.toLowerCase().includes("encrypted.asc")
+      ) {
+        EnigmailLog.DEBUG(
+          "persistentCrypto.jsm: isBrokenByExchange: found message broken by MS-Exchange\n"
+        );
         return true;
       }
     } catch (ex) {}
 
     return false;
   },
 
-  isPgpMime: function(mimePart) {
+  isPgpMime(mimePart) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: isPgpMime()\n");
 
     try {
       if (mimePart.headers.has("content-type")) {
-        if (mimePart.headers.get("content-type").type.toLowerCase() === "multipart/encrypted" &&
-          mimePart.headers.get("content-type").get("protocol").toLowerCase() === "application/pgp-encrypted" &&
-          mimePart.subParts.length === 2) {
+        if (
+          mimePart.headers.get("content-type").type.toLowerCase() ===
+            "multipart/encrypted" &&
+          mimePart.headers
+            .get("content-type")
+            .get("protocol")
+            .toLowerCase() === "application/pgp-encrypted" &&
+          mimePart.subParts.length === 2
+        ) {
           return true;
         }
       }
     } catch (x) {}
     return false;
   },
 
-  decryptPGPMIME: async function(mimePart) {
-    EnigmailLog.DEBUG("persistentCrypto.jsm: decryptPGPMIME(" + mimePart.partNum + ")\n");
+  async decryptPGPMIME(mimePart) {
+    EnigmailLog.DEBUG(
+      "persistentCrypto.jsm: decryptPGPMIME(" + mimePart.partNum + ")\n"
+    );
 
-    if (!mimePart.subParts[1]) throw new Error("Not a correct PGP/MIME message");
+    if (!mimePart.subParts[1]) {
+      throw new Error("Not a correct PGP/MIME message");
+    }
 
-    const uiFlags = EnigmailConstants.UI_INTERACTIVE | EnigmailConstants.UI_UNVERIFIED_ENC_OK |
+    const uiFlags =
+      EnigmailConstants.UI_INTERACTIVE |
+      EnigmailConstants.UI_UNVERIFIED_ENC_OK |
       EnigmailConstants.UI_IGNORE_MDC_ERROR;
     let exitCodeObj = {};
     let statusFlagsObj = {};
     let userIdObj = {};
     let sigDetailsObj = {};
     let errorMsgObj = {};
     let keyIdObj = {};
     let blockSeparationObj = {
-      value: ""
+      value: "",
     };
     let encToDetailsObj = {};
     var signatureObj = {};
     signatureObj.value = "";
 
-
-    let data = getDecryption().decryptMessage(null, uiFlags, mimePart.subParts[1].body, signatureObj, exitCodeObj, statusFlagsObj,
-      keyIdObj, userIdObj, sigDetailsObj, errorMsgObj, blockSeparationObj, encToDetailsObj);
+    let data = getDecryption().decryptMessage(
+      null,
+      uiFlags,
+      mimePart.subParts[1].body,
+      signatureObj,
+      exitCodeObj,
+      statusFlagsObj,
+      keyIdObj,
+      userIdObj,
+      sigDetailsObj,
+      errorMsgObj,
+      blockSeparationObj,
+      encToDetailsObj
+    );
 
     if (!data || data.length === 0) {
       if (statusFlagsObj.value & EnigmailConstants.DISPLAY_MESSAGE) {
         getDialog().alert(null, errorMsgObj.value);
         throw new Error("Decryption impossible");
       }
     }
 
-    EnigmailLog.DEBUG("persistentCrypto.jsm: analyzeDecryptedData: got " + data.length + " bytes\n");
+    EnigmailLog.DEBUG(
+      "persistentCrypto.jsm: analyzeDecryptedData: got " +
+        data.length +
+        " bytes\n"
+    );
 
     if (EnigmailLog.getLogLevel() > 5) {
       EnigmailLog.DEBUG("*** start data ***\n'" + data + "'\n***end data***\n");
     }
 
     if (data.length === 0) {
       // fail if no data found
       return;
@@ -377,17 +457,19 @@ CryptMessageIntoFolder.prototype = {
     } else {
       ++bodyIndex;
     }
 
     if (data.substr(bodyIndex).search(/\r?\n$/) === 0) {
       return;
     }
 
-    let m = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+    let m = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     m.initialize(data.substr(0, bodyIndex));
     let ct = m.extractHeader("content-type", false) || "";
     let part = mimePart.partNum;
 
     if (part.length > 0 && part.search(/[^01.]/) < 0) {
       if (ct.search(/protected-headers/i) >= 0) {
         if (m.hasHeader("subject")) {
           let subject = m.extractHeader("subject", false) || "";
@@ -399,43 +481,47 @@ CryptMessageIntoFolder.prototype = {
         if (subject) {
           subject = subject.replace(/^(Re: )+/, "Re: ");
           this.mimeTree.headers._rawHeaders.set("subject", [subject]);
         }
       }
     }
 
     let boundary = getBoundary(mimePart);
-    if (!boundary)
+    if (!boundary) {
       boundary = EnigmailMime.createBoundary();
+    }
 
     // append relevant headers
     mimePart.headers.get("content-type").type = "multipart/mixed";
-    mimePart.headers._rawHeaders.set("content-type", ['multipart/mixed; boundary="' + boundary + '"']);
-    mimePart.subParts = [{
-      body: data,
-      decryptedPgpMime: true,
-      partNum: mimePart.partNum + ".1",
-      headers: {
-        _rawHeaders: new Map(),
-        get: function() {
-          return null;
+    mimePart.headers._rawHeaders.set("content-type", [
+      'multipart/mixed; boundary="' + boundary + '"',
+    ]);
+    mimePart.subParts = [
+      {
+        body: data,
+        decryptedPgpMime: true,
+        partNum: mimePart.partNum + ".1",
+        headers: {
+          _rawHeaders: new Map(),
+          get() {
+            return null;
+          },
+          has() {
+            return false;
+          },
         },
-        has: function() {
-          return false;
-        }
+        subParts: [],
       },
-      subParts: []
-    }];
-
+    ];
 
     this.messageDecrypted = true;
   },
 
-  decryptAttachment: function(mimePart) {
+  decryptAttachment(mimePart) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: decryptAttachment()\n");
     throw new Error("Not implemented");
 
     /*
     let attachmentHead = mimePart.body.substr(0, 30);
     if (attachmentHead.search(/-----BEGIN PGP \w{5,10} KEY BLOCK-----/) >= 0) {
       // attachment appears to be a PGP key file, we just go-a-head
       return;
@@ -463,21 +549,20 @@ CryptMessageIntoFolder.prototype = {
       }
       ct += `; ${i[0]}="${i[1]}"`;
     }
 
     mimePart.headers._rawHeaders.set("content-type", [ct]);
     */
   },
 
-
-  decryptINLINE: function(mimePart) {
+  decryptINLINE(mimePart) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: decryptINLINE()\n");
 
-    if (("decryptedPgpMime" in mimePart) && mimePart.decryptedPgpMime) {
+    if ("decryptedPgpMime" in mimePart && mimePart.decryptedPgpMime) {
       return 0;
     }
 
     if ("body" in mimePart && mimePart.body.length > 0) {
       let ct = getContentType(mimePart);
 
       if (ct === "text/html") {
         mimePart.body = this.stripHTMLFromArmoredBlocks(mimePart.body);
@@ -485,23 +570,25 @@ CryptMessageIntoFolder.prototype = {
 
       var exitCodeObj = {};
       var statusFlagsObj = {};
       var userIdObj = {};
       var sigDetailsObj = {};
       var errorMsgObj = {};
       var keyIdObj = {};
       var blockSeparationObj = {
-        value: ""
+        value: "",
       };
       var encToDetailsObj = {};
       var signatureObj = {};
       signatureObj.value = "";
 
-      const uiFlags = EnigmailConstants.UI_INTERACTIVE | EnigmailConstants.UI_UNVERIFIED_ENC_OK |
+      const uiFlags =
+        EnigmailConstants.UI_INTERACTIVE |
+        EnigmailConstants.UI_UNVERIFIED_ENC_OK |
         EnigmailConstants.UI_IGNORE_MDC_ERROR;
 
       var plaintexts = [];
       var blocks = EnigmailArmor.locateArmoredBlocks(mimePart.body);
       var tmp = [];
 
       for (let i = 0; i < blocks.length; i++) {
         if (blocks[i].blocktype == "MESSAGE") {
@@ -515,255 +602,316 @@ CryptMessageIntoFolder.prototype = {
         return 0;
       }
 
       let charset = "utf-8";
 
       for (let i = 0; i < blocks.length; i++) {
         let plaintext = null;
         do {
-          let ciphertext = mimePart.body.substring(blocks[i].begin, blocks[i].end + 1);
+          let ciphertext = mimePart.body.substring(
+            blocks[i].begin,
+            blocks[i].end + 1
+          );
 
           if (ciphertext.length === 0) {
             break;
           }
 
           let hdr = ciphertext.search(/(\r\r|\n\n|\r\n\r\n)/);
           if (hdr > 0) {
-            let chset = ciphertext.substr(0, hdr).match(/^(charset:)(.*)$/mi);
+            let chset = ciphertext.substr(0, hdr).match(/^(charset:)(.*)$/im);
             if (chset && chset.length == 3) {
               charset = chset[2].trim();
             }
           }
-          plaintext = getDecryption().decryptMessage(null, uiFlags, ciphertext, signatureObj, exitCodeObj, statusFlagsObj,
-            keyIdObj, userIdObj, sigDetailsObj, errorMsgObj, blockSeparationObj, encToDetailsObj);
+          plaintext = getDecryption().decryptMessage(
+            null,
+            uiFlags,
+            ciphertext,
+            signatureObj,
+            exitCodeObj,
+            statusFlagsObj,
+            keyIdObj,
+            userIdObj,
+            sigDetailsObj,
+            errorMsgObj,
+            blockSeparationObj,
+            encToDetailsObj
+          );
           if (!plaintext || plaintext.length === 0) {
             if (statusFlagsObj.value & EnigmailConstants.DISPLAY_MESSAGE) {
               getDialog().alert(null, errorMsgObj.value);
               this.messageDecrypted = false;
               return -1;
             }
 
-            if (statusFlagsObj.value & (EnigmailConstants.DECRYPTION_FAILED | EnigmailConstants.MISSING_MDC)) {
-              EnigmailLog.DEBUG("persistentCrypto.jsm: decryptINLINE: no MDC protection, decrypting anyway\n");
+            if (
+              statusFlagsObj.value &
+              (EnigmailConstants.DECRYPTION_FAILED |
+                EnigmailConstants.MISSING_MDC)
+            ) {
+              EnigmailLog.DEBUG(
+                "persistentCrypto.jsm: decryptINLINE: no MDC protection, decrypting anyway\n"
+              );
             }
             if (statusFlagsObj.value & EnigmailConstants.DECRYPTION_FAILED) {
               // since we cannot find out if the user wants to cancel
               // we should ask
-              let msg = EnigmailLocale.getString("converter.decryptBody.failed", this.subject);
+              let msg = EnigmailLocale.getString(
+                "converter.decryptBody.failed",
+                this.subject
+              );
 
-              if (!getDialog().confirmDlg(null, msg,
-                  EnigmailLocale.getString("dlg.button.retry"), EnigmailLocale.getString("dlg.button.skip"))) {
+              if (
+                !getDialog().confirmDlg(
+                  null,
+                  msg,
+                  EnigmailLocale.getString("dlg.button.retry"),
+                  EnigmailLocale.getString("dlg.button.skip")
+                )
+              ) {
                 this.messageDecrypted = false;
                 return -1;
               }
-            } else if (statusFlagsObj.value & EnigmailConstants.DECRYPTION_INCOMPLETE) {
+            } else if (
+              statusFlagsObj.value & EnigmailConstants.DECRYPTION_INCOMPLETE
+            ) {
               this.messageDecrypted = false;
               return -1;
             } else {
               plaintext = " ";
             }
           }
 
           if (ct === "text/html") {
-            plaintext = plaintext.replace(/\n/ig, "<br/>\n");
+            plaintext = plaintext.replace(/\n/gi, "<br/>\n");
           }
 
           let subject = "";
           if (this.mimeTree.headers.has("subject")) {
             subject = this.mimeTree.headers.get("subject");
           }
 
-          if (i == 0 && this.mimeTree.headers.subject === "pEp" &&
-            mimePart.partNum.length > 0 && mimePart.partNum.search(/[^01.]/) < 0) {
-
+          if (
+            i == 0 &&
+            subject === "pEp" &&
+            mimePart.partNum.length > 0 &&
+            mimePart.partNum.search(/[^01.]/) < 0
+          ) {
             let m = EnigmailMime.extractSubjectFromBody(plaintext);
             if (m) {
               plaintext = m.messageBody;
               this.mimeTree.headers._rawHeaders.set("subject", [m.subject]);
             }
           }
 
           if (plaintext) {
             plaintexts.push(plaintext);
           }
         } while (!plaintext || plaintext === "");
       }
 
-
-
-      var decryptedMessage = mimePart.body.substring(0, blocks[0].begin) + plaintexts[0];
+      var decryptedMessage =
+        mimePart.body.substring(0, blocks[0].begin) + plaintexts[0];
       for (let i = 1; i < blocks.length; i++) {
-        decryptedMessage += mimePart.body.substring(blocks[i - 1].end + 1, blocks[i].begin + 1) + plaintexts[i];
+        decryptedMessage +=
+          mimePart.body.substring(blocks[i - 1].end + 1, blocks[i].begin + 1) +
+          plaintexts[i];
       }
 
-      decryptedMessage += mimePart.body.substring(blocks[(blocks.length - 1)].end + 1);
+      decryptedMessage += mimePart.body.substring(
+        blocks[blocks.length - 1].end + 1
+      );
 
       // enable base64 encoding if non-ASCII character(s) found
       let j = decryptedMessage.search(/[^\x01-\x7F]/); // eslint-disable-line no-control-regex
       if (j >= 0) {
-        mimePart.headers._rawHeaders.set('content-transfer-encoding', ['base64']);
+        mimePart.headers._rawHeaders.set("content-transfer-encoding", [
+          "base64",
+        ]);
       } else {
-        mimePart.headers._rawHeaders.set('content-transfer-encoding', ['8bit']);
+        mimePart.headers._rawHeaders.set("content-transfer-encoding", ["8bit"]);
       }
       mimePart.body = decryptedMessage;
 
-      let origCharset = getCharset(getHeaderValue(mimePart, 'content-type'));
+      let origCharset = getCharset(getHeaderValue(mimePart, "content-type"));
       if (origCharset) {
-        mimePart.headers_rawHeaders.set('content-type', getHeaderValue(mimePart, 'content-type').replace(origCharset, charset));
+        mimePart.headers_rawHeaders.set(
+          "content-type",
+          getHeaderValue(mimePart, "content-type").replace(origCharset, charset)
+        );
       } else {
-        mimePart.headers._rawHeaders.set('content-type', getHeaderValue(mimePart, 'content-type') + "; charset=" + charset);
+        mimePart.headers._rawHeaders.set(
+          "content-type",
+          getHeaderValue(mimePart, "content-type") + "; charset=" + charset
+        );
       }
 
       this.messageDecrypted = true;
       return 1;
     }
 
     let ct = getContentType(mimePart);
-    EnigmailLog.DEBUG("persistentCrypto.jsm: Decryption skipped:  " + ct + "\n");
+    EnigmailLog.DEBUG(
+      "persistentCrypto.jsm: Decryption skipped:  " + ct + "\n"
+    );
 
     return 0;
   },
 
-  stripHTMLFromArmoredBlocks: function(text) {
-
+  stripHTMLFromArmoredBlocks(text) {
     var index = 0;
     var begin = text.indexOf("-----BEGIN PGP");
     var end = text.indexOf("-----END PGP");
 
     while (begin > -1 && end > -1) {
       let sub = text.substring(begin, end);
 
-      sub = sub.replace(/(<([^>]+)>)/ig, "");
-      sub = sub.replace(/&[A-z]+;/ig, "");
+      sub = sub.replace(/(<([^>]+)>)/gi, "");
+      sub = sub.replace(/&[A-z]+;/gi, "");
 
       text = text.substring(0, begin) + sub + text.substring(end);
 
       index = end + 10;
       begin = text.indexOf("-----BEGIN PGP", index);
       end = text.indexOf("-----END PGP", index);
     }
 
     return text;
   },
 
-
   /******
    *
    *    We have the technology we can rebuild.
    *
    *    Function to reassemble the message from the MIME Tree
    *    into a String.
    *
    ******/
 
-  mimeToString: function(mimePart, includeHeaders) {
-    EnigmailLog.DEBUG("persistentCrypto.jsm: mimeToString: part: '" + mimePart.partNum + "'\n");
+  mimeToString(mimePart, includeHeaders) {
+    EnigmailLog.DEBUG(
+      "persistentCrypto.jsm: mimeToString: part: '" + mimePart.partNum + "'\n"
+    );
 
     let msg = "";
     let rawHdr = mimePart.headers._rawHeaders;
 
     if (includeHeaders && rawHdr.size > 0) {
       for (let hdr of rawHdr.keys()) {
         msg += formatMimeHeader(hdr, rawHdr.get(hdr)) + "\r\n";
       }
 
       msg += "\r\n";
     }
 
     if (mimePart.body.length > 0) {
       let encoding = getTransferEncoding(mimePart);
-      if (!encoding) encoding = "8bit";
+      if (!encoding) {
+        encoding = "8bit";
+      }
 
       if (encoding === "quoted-printable") {
-        mimePart.headers._rawHeaders.set("content-transfer-encoding", ["base64"]);
+        mimePart.headers._rawHeaders.set("content-transfer-encoding", [
+          "base64",
+        ]);
         encoding = "base64";
       }
 
       if (encoding === "base64") {
         msg += EnigmailData.encodeBase64(mimePart.body);
       } else {
         msg += mimePart.body;
       }
-
     }
 
     if (mimePart.subParts.length > 0) {
-      let boundary = EnigmailMime.getBoundary(rawHdr.get("content-type").join(""));
+      let boundary = EnigmailMime.getBoundary(
+        rawHdr.get("content-type").join("")
+      );
 
       for (let i in mimePart.subParts) {
         msg += `--${boundary}\r\n`;
         msg += this.mimeToString(mimePart.subParts[i], true);
         if (msg.search(/[\r\n]$/) < 0) {
           msg += "\r\n";
         }
       }
 
       msg += `--${boundary}--\r\n`;
     }
     return msg;
   },
 
-  storeMessage: function(msg) {
+  storeMessage(msg) {
     let self = this;
 
     return new Promise((resolve, reject) => {
       //XXX Do we wanna use the tmp for this?
-      let tempFile = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
+      let tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile);
       tempFile.append("message.eml");
       tempFile.createUnique(0, 384); // == 0600, octal is deprecated
 
       // ensure that file gets deleted on exit, if something goes wrong ...
-      let extAppLauncher = Cc["@mozilla.org/mime;1"].getService(Ci.nsPIExternalAppLauncher);
+      let extAppLauncher = Cc["@mozilla.org/mime;1"].getService(
+        Ci.nsPIExternalAppLauncher
+      );
 
-      let foStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
+      let foStream = Cc[
+        "@mozilla.org/network/file-output-stream;1"
+      ].createInstance(Ci.nsIFileOutputStream);
       foStream.init(tempFile, 2, 0x200, false); // open as "write only"
       foStream.write(msg, msg.length);
       foStream.close();
 
       extAppLauncher.deleteTemporaryFileOnExit(tempFile);
 
       //
       //  This was taken from the HeaderToolsLite Example Addon "original by Frank DiLecce"
       //
       // this is interesting: nsIMsgFolder.copyFileMessage seems to have a bug on Windows, when
       // the nsIFile has been already used by foStream (because of Windows lock system?), so we
       // must initialize another nsIFile object, pointing to the temporary file
       let fileSpec = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
       fileSpec.initWithPath(tempFile.path);
 
-      const copySvc = Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(Ci.nsIMsgCopyService);
-
       let copyListener = {
-        QueryInterface: function(iid) {
-          if (iid.equals(Ci.nsIMsgCopyServiceListener) || iid.equals(Ci.nsISupports)) {
-            return this;
-          }
-          EnigmailLog.DEBUG("persistentCrypto.jsm: copyListener error\n");
-          throw Components.results.NS_NOINTERFACE;
+        QueryInterface: ChromeUtils.generateQI(["nsIMsgCopyServiceListener"]),
+        GetMessageId(messageId) {},
+        OnProgress(progress, progressMax) {},
+        OnStartCopy() {
+          EnigmailLog.DEBUG(
+            "persistentCrypto.jsm: copyListener: OnStartCopy()\n"
+          );
         },
-        GetMessageId: function(messageId) {},
-        OnProgress: function(progress, progressMax) {},
-        OnStartCopy: function() {
-          EnigmailLog.DEBUG("persistentCrypto.jsm: copyListener: OnStartCopy()\n");
+        SetMessageKey(key) {
+          EnigmailLog.DEBUG(
+            "persistentCrypto.jsm: copyListener: SetMessageKey(" + key + ")\n"
+          );
         },
-        SetMessageKey: function(key) {
-          EnigmailLog.DEBUG("persistentCrypto.jsm: copyListener: SetMessageKey(" + key + ")\n");
-        },
-        OnStopCopy: function(statusCode) {
-          EnigmailLog.DEBUG("persistentCrypto.jsm: copyListener: OnStopCopy()\n");
+        OnStopCopy(statusCode) {
+          EnigmailLog.DEBUG(
+            "persistentCrypto.jsm: copyListener: OnStopCopy()\n"
+          );
           if (statusCode !== 0) {
-            EnigmailLog.DEBUG("persistentCrypto.jsm: Error copying message: " + statusCode + "\n");
+            EnigmailLog.DEBUG(
+              "persistentCrypto.jsm: Error copying message: " +
+                statusCode +
+                "\n"
+            );
             try {
               tempFile.remove(false);
             } catch (ex) {
               try {
                 fileSpec.remove(false);
               } catch (e2) {
-                EnigmailLog.DEBUG("persistentCrypto.jsm: Could not delete temp file\n");
+                EnigmailLog.DEBUG(
+                  "persistentCrypto.jsm: Could not delete temp file\n"
+                );
               }
             }
             resolve(true);
             return;
           }
           EnigmailLog.DEBUG("persistentCrypto.jsm: Copy complete\n");
 
           if (self.move) {
@@ -771,57 +919,63 @@ CryptMessageIntoFolder.prototype = {
           }
 
           try {
             tempFile.remove(false);
           } catch (ex) {
             try {
               fileSpec.remove(false);
             } catch (e2) {
-              EnigmailLog.DEBUG("persistentCrypto.jsm: Could not delete temp file\n");
+              EnigmailLog.DEBUG(
+                "persistentCrypto.jsm: Could not delete temp file\n"
+              );
             }
           }
 
           EnigmailLog.DEBUG("persistentCrypto.jsm: Cave Johnson. We're done\n");
           resolve(true);
-        }
+        },
       };
 
       EnigmailLog.DEBUG("persistentCrypto.jsm: copySvc ready for copy\n");
       try {
         if (self.mimeTree.headers.has("subject")) {
           self.hdr.subject = self.mimeTree.headers.get("subject");
         }
       } catch (ex) {}
 
-      EnigmailCompat.copyFileToMailFolder(fileSpec, EnigmailCompat.getExistingFolder(self.destFolder),
-        0, "", copyListener, null);
+      EnigmailCompat.copyFileToMailFolder(
+        fileSpec,
+        EnigmailCompat.getExistingFolder(self.destFolder),
+        0,
+        "",
+        copyListener,
+        null
+      );
     });
   },
 
-  fixExchangeMessage: function(mimePart) {
+  fixExchangeMessage(mimePart) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: fixExchangeMessage()\n");
 
     const FixEx = getFixExchangeMsg();
 
     let msg = this.mimeToString(mimePart, true);
-    let app = FixEx.determineCreatorApp(msg);
 
     try {
       let fixedMsg = FixEx.getRepairedMessage(msg);
       let replacement = EnigmailMime.getMimeTree(fixedMsg, true);
 
       for (let i in replacement) {
         mimePart[i] = replacement[i];
       }
     } catch (ex) {}
-  }
+  },
 };
 
-
 /**
  * Format a mime header
  *
  * e.g. content-type -> Content-Type
  */
 
 function formatHeader(headerLabel) {
   return headerLabel.replace(/^.|(-.)/g, function(match) {
@@ -829,246 +983,220 @@ function formatHeader(headerLabel) {
   });
 }
 
 function formatMimeHeader(headerLabel, headerValue) {
   if (Array.isArray(headerValue)) {
     headerValue = headerValue.join("");
   }
   if (headerLabel.search(/^(sender|from|reply-to|to|cc|bcc)$/i) === 0) {
-    return formatHeader(headerLabel) + ": " + EnigmailMime.formatHeaderData(EnigmailMime.formatEmailAddress(headerValue));
-  } else {
-    return formatHeader(headerLabel) + ": " + EnigmailMime.formatHeaderData(EnigmailMime.encodeHeaderValue(headerValue));
+    return (
+      formatHeader(headerLabel) +
+      ": " +
+      EnigmailMime.formatHeaderData(
+        EnigmailMime.formatEmailAddress(headerValue)
+      )
+    );
   }
+  return (
+    formatHeader(headerLabel) +
+    ": " +
+    EnigmailMime.formatHeaderData(EnigmailMime.encodeHeaderValue(headerValue))
+  );
 }
 
-
 function prettyPrintHeader(headerLabel, headerData) {
-  let hdrData = "";
   if (Array.isArray(headerData)) {
     let h = [];
     for (let i in headerData) {
       h.push(formatMimeHeader(headerLabel, GlodaUtils.deMime(headerData[i])));
     }
     return h.join("\r\n");
-  } else {
-    return formatMimeHeader(headerLabel, GlodaUtils.deMime(String(headerData)));
   }
+  return formatMimeHeader(headerLabel, GlodaUtils.deMime(String(headerData)));
 }
 
 function getHeaderValue(mimeStruct, header) {
   EnigmailLog.DEBUG("persistentCrypto.jsm: getHeaderValue: '" + header + "'\n");
 
   try {
     if (mimeStruct.headers.has(header)) {
       let hdrVal = mimeStruct.headers.get(header);
       if (typeof hdrVal == "string") {
         return hdrVal;
-      } else {
-        return mimeStruct.headers[header].join(" ");
       }
-    } else {
-      return "";
+      return mimeStruct.headers[header].join(" ");
     }
+    return "";
   } catch (ex) {
-    EnigmailLog.DEBUG("persistentCrypto.jsm: getHeaderValue: header not present\n");
+    EnigmailLog.DEBUG(
+      "persistentCrypto.jsm: getHeaderValue: header not present\n"
+    );
     return "";
   }
 }
 
-/***
- * get the formatted headers for MimeMessage objects
- *
- * @headerArr:        Array of headers (key/value pairs), such as mime.headers
- * @ignoreHeadersArr: Array of headers to exclude from returning
- *
- * @return:   String containing formatted header list
- */
-function getRfc822Headers(headerArr, contentType, ignoreHeadersArr) {
-  let hdrs = "";
-
-  let ignore = [];
-  if (contentType.indexOf("multipart/") >= 0) {
-    ignore = ['content-transfer-encoding',
-      'content-disposition',
-      'content-description'
-    ];
-  }
-
-  if (ignoreHeadersArr) {
-    ignore = ignore.concat(ignoreHeadersArr);
-  }
-
-  for (let i in headerArr) {
-    if (ignore.indexOf(i) < 0) {
-      hdrs += prettyPrintHeader(i, headerArr[i]) + "\r\n";
-    }
-  }
-
-  return hdrs;
-}
-
 function getContentType(mime) {
   try {
-    if (mime && ("headers" in mime) && mime.headers.has("content-type")) {
+    if (mime && "headers" in mime && mime.headers.has("content-type")) {
       return mime.headers.get("content-type").type.toLowerCase();
     }
   } catch (e) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: getContentType: " + e + "\n");
   }
   return null;
 }
 
 // return the content of the boundary parameter
 function getBoundary(mime) {
   try {
-    if (mime && ("headers" in mime) && mime.headers.has("content-type")) {
+    if (mime && "headers" in mime && mime.headers.has("content-type")) {
       return mime.headers.get("content-type").get("boundary");
     }
   } catch (e) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: getBoundary: " + e + "\n");
   }
   return null;
 }
 
 function getCharset(mime) {
   try {
-    if (mime && ("headers" in mime) && mime.headers.has("content-type")) {
+    if (mime && "headers" in mime && mime.headers.has("content-type")) {
       let c = mime.headers.get("content-type").get("charset");
-      if (c) return c.toLowerCase();
+      if (c) {
+        return c.toLowerCase();
+      }
     }
   } catch (e) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: getCharset: " + e + "\n");
   }
   return null;
 }
 
-function getProtocol(mime) {
-  try {
-    if (mime && ("headers" in mime) && mime.headers.has("content-type")) {
-      let c = mime.headers.get("content-type").get("protocol");
-      if (c) return c.toLowerCase();
-    }
-  } catch (e) {
-    EnigmailLog.DEBUG("persistentCrypto.jsm: getProtocol: " + e + "\n");
-  }
-  return "";
-}
-
 function getTransferEncoding(mime) {
   try {
-    if (mime && ("headers" in mime) && mime.headers._rawHeaders.has("content-transfer-encoding")) {
+    if (
+      mime &&
+      "headers" in mime &&
+      mime.headers._rawHeaders.has("content-transfer-encoding")
+    ) {
       let c = mime.headers._rawHeaders.get("content-transfer-encoding")[0];
-      if (c) return c.toLowerCase();
+      if (c) {
+        return c.toLowerCase();
+      }
     }
   } catch (e) {
     EnigmailLog.DEBUG("persistentCrypto.jsm: getTransferEncoding: " + e + "\n");
   }
   return "8Bit";
 }
 
 function isAttachment(mime) {
   try {
-    if (mime && ("headers" in mime)) {
-      if (mime.fullContentType.search(/^multipart\//i) === 0) return false;
-      if (mime.fullContentType.search(/^text\//i) < 0) return true;
+    if (mime && "headers" in mime) {
+      if (mime.fullContentType.search(/^multipart\//i) === 0) {
+        return false;
+      }
+      if (mime.fullContentType.search(/^text\//i) < 0) {
+        return true;
+      }
 
       if (mime.headers.has("content-disposition")) {
         let c = mime.headers.get("content-disposition")[0];
         if (c) {
           if (c.search(/^attachment/i) === 0) {
             return true;
           }
         }
       }
     }
   } catch (x) {}
   return false;
 }
 
-
-function getAttachmentName(mime) {
-  try {
-    if (mime && ("headers" in mime) && mime.headers.has("content-disposition")) {
-      let c = mime.headers.get("content-disposition")[0];
-      if (c) {
-        if (c.search(/^attachment/i) === 0) {
-          return EnigmailMime.getParameter(c, "filename");
-        }
-      }
-    }
-  } catch (e) {
-    EnigmailLog.DEBUG("persistentCrypto.jsm: getAttachmentName: " + e + "\n");
-  }
-  return null;
-}
-
-
 function getPepSubject(mimeString) {
   EnigmailLog.DEBUG("persistentCrypto.jsm: getPepSubject()\n");
 
   let subject = null;
 
   let emitter = {
     ct: "",
     firstPlainText: false,
-    startPart: function(partNum, headers) {
-      EnigmailLog.DEBUG("persistentCrypto.jsm: getPepSubject.startPart: partNum=" + partNum + "\n");
+    startPart(partNum, headers) {
+      EnigmailLog.DEBUG(
+        "persistentCrypto.jsm: getPepSubject.startPart: partNum=" +
+          partNum +
+          "\n"
+      );
       try {
         this.ct = String(headers.getRawHeader("content-type")).toLowerCase();
         if (!subject && !this.firstPlainText) {
           let s = headers.getRawHeader("subject");
           if (s) {
             subject = String(s);
             this.firstPlainText = true;
           }
         }
       } catch (ex) {
         this.ct = "";
       }
     },
 
-    endPart: function(partNum) {},
+    endPart(partNum) {},
 
-    deliverPartData: function(partNum, data) {
-      EnigmailLog.DEBUG("persistentCrypto.jsm: getPepSubject.deliverPartData: partNum=" + partNum + " ct=" + this.ct + "\n");
+    deliverPartData(partNum, data) {
+      EnigmailLog.DEBUG(
+        "persistentCrypto.jsm: getPepSubject.deliverPartData: partNum=" +
+          partNum +
+          " ct=" +
+          this.ct +
+          "\n"
+      );
       if (!this.firstPlainText && this.ct.search(/^text\/plain/) === 0) {
         // check data
         this.firstPlainText = true;
 
         let o = EnigmailMime.extractSubjectFromBody(data);
         if (o) {
           subject = o.subject;
         }
       }
-    }
+    },
   };
 
   let opt = {
     strformat: "unicode",
-    bodyformat: "decode"
+    bodyformat: "decode",
   };
 
   try {
     let p = new jsmime.MimeParser(emitter, opt);
     p.deliverData(mimeString);
   } catch (ex) {}
 
   return subject;
 }
 
 /**
  * Lazy deletion of original messages
  */
 function deleteOriginalMail(msgHdr) {
-  EnigmailLog.DEBUG("persistentCrypto.jsm: deleteOriginalMail(" + msgHdr.messageKey + ")\n");
+  EnigmailLog.DEBUG(
+    "persistentCrypto.jsm: deleteOriginalMail(" + msgHdr.messageKey + ")\n"
+  );
 
   let delMsg = function() {
     try {
-      EnigmailLog.DEBUG("persistentCrypto.jsm: deleting original message " + msgHdr.messageKey + "\n");
+      EnigmailLog.DEBUG(
+        "persistentCrypto.jsm: deleting original message " +
+          msgHdr.messageKey +
+          "\n"
+      );
       EnigmailStdlib.msgHdrsDelete([msgHdr]);
     } catch (e) {
-      EnigmailLog.DEBUG("persistentCrypto.jsm: deletion failed. Error: " + e.toString() + "\n");
+      EnigmailLog.DEBUG(
+        "persistentCrypto.jsm: deletion failed. Error: " + e.toString() + "\n"
+      );
     }
   };
 
   EnigmailTimer.setTimeout(delMsg, 500);
 }
--- a/mail/extensions/openpgp/content/modules/pgpmimeHandler.jsm
+++ b/mail/extensions/openpgp/content/modules/pgpmimeHandler.jsm
@@ -4,94 +4,115 @@
 
 "use strict";
 
 /**
  *  Module for handling PGP/MIME encrypted and/or signed messages
  *  implemented as an XPCOM object
  */
 
-const {
-  manager: Cm,
-  results: Cr,
-  Constructor: CC
-} = Components;
+const { manager: Cm } = Components;
 Cm.QueryInterface(Ci.nsIComponentRegistrar);
 
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 var EXPORTED_SYMBOLS = ["EnigmailPgpmimeHander"];
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailMimeDecrypt = ChromeUtils.import("chrome://openpgp/content/modules/mimeDecrypt.jsm").EnigmailMimeDecrypt;
-const EnigmailVerify = ChromeUtils.import("chrome://openpgp/content/modules/mimeVerify.jsm").EnigmailVerify;
-const EnigmailWksMimeHandler = ChromeUtils.import("chrome://openpgp/content/modules/wksMimeHandler.jsm").EnigmailWksMimeHandler;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailSingletons = ChromeUtils.import("chrome://openpgp/content/modules/singletons.jsm").EnigmailSingletons;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailMimeDecrypt = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mimeDecrypt.jsm"
+).EnigmailMimeDecrypt;
+const EnigmailVerify = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mimeVerify.jsm"
+).EnigmailVerify;
+const EnigmailWksMimeHandler = ChromeUtils.import(
+  "chrome://openpgp/content/modules/wksMimeHandler.jsm"
+).EnigmailWksMimeHandler;
+const EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailSingletons = ChromeUtils.import(
+  "chrome://openpgp/content/modules/singletons.jsm"
+).EnigmailSingletons;
 
-const PGPMIME_JS_DECRYPTOR_CONTRACTID = "@mozilla.org/mime/pgp-mime-js-decrypt;1";
-const PGPMIME_JS_DECRYPTOR_CID = Components.ID("{7514cbeb-2bfd-4b2c-829b-1a4691fa0ac8}");
+const PGPMIME_JS_DECRYPTOR_CONTRACTID =
+  "@mozilla.org/mime/pgp-mime-js-decrypt;1";
+const PGPMIME_JS_DECRYPTOR_CID = Components.ID(
+  "{7514cbeb-2bfd-4b2c-829b-1a4691fa0ac8}"
+);
 
 ////////////////////////////////////////////////////////////////////
 // handler for PGP/MIME encrypted and PGP/MIME signed messages
 // data is processed from libmime -> nsPgpMimeProxy
 
 var gConv;
 var inStream;
 
 var gLastEncryptedUri = "";
 
 const throwErrors = {
-  onDataAvailable: function() {
+  onDataAvailable() {
     throw new Error("error");
   },
-  onStartRequest: function() {
+  onStartRequest() {
     throw new Error("error");
   },
-  onStopRequest: function() {
+  onStopRequest() {
     throw new Error("error");
-  }
+  },
 };
 
 /**
  * UnknownProtoHandler is a default handler for unkonwn protocols. It ensures that the
  * signed message part is always displayed without any further action.
  */
 function UnknownProtoHandler() {
   if (!gConv) {
-    gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
+    gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
+      Ci.nsIStringInputStream
+    );
   }
 
   if (!inStream) {
-    inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
+    inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+      Ci.nsIScriptableInputStream
+    );
   }
 }
 
 UnknownProtoHandler.prototype = {
-  onStartRequest: function(request, ctxt) {
+  onStartRequest(request, ctxt) {
     this.mimeSvc = request.QueryInterface(Ci.nsIPgpMimeProxy);
     if (!("outputDecryptedData" in this.mimeSvc)) {
       this.mimeSvc.onStartRequest(null, ctxt);
     }
     this.bound = EnigmailMime.getBoundary(this.mimeSvc.contentType);
     /*
       readMode:
         0: before message
         1: inside message
         2: afer message
     */
     this.readMode = 0;
   },
 
-  onDataAvailable: function(p1, p2, p3, p4) {
+  onDataAvailable(p1, p2, p3, p4) {
     this.processData(p1, p2, p3, p4);
   },
 
-  processData: function (req, stream, offset, count) {
+  processData(req, stream, offset, count) {
     if (count > 0) {
       inStream.init(stream);
       let data = inStream.read(count);
       let l = data.replace(/\r\n/g, "\n").split(/\n/);
 
       if (data.search(/\n$/) >= 0) {
         l.pop();
       }
@@ -100,68 +121,65 @@ UnknownProtoHandler.prototype = {
       let endIndex = l.length;
 
       if (this.readMode < 2) {
         for (let i = 0; i < l.length; i++) {
           if (l[i].indexOf("--") === 0 && l[i].indexOf(this.bound) === 2) {
             ++this.readMode;
             if (this.readMode === 1) {
               startIndex = i + 1;
-            }
-            else if (this.readMode === 2) {
+            } else if (this.readMode === 2) {
               endIndex = i - 1;
             }
           }
         }
 
         if (this.readMode >= 1 && startIndex < l.length) {
           let out = l.slice(startIndex, endIndex).join("\n") + "\n";
 
           if ("outputDecryptedData" in this.mimeSvc) {
             // TB >= 57
             this.mimeSvc.outputDecryptedData(out, out.length);
-          }
-          else {
+          } else {
             gConv.setData(out, out.length);
             this.mimeSvc.onDataAvailable(null, null, gConv, 0, out.length);
           }
         }
       }
     }
   },
 
-  onStopRequest: function() {
+  onStopRequest() {
     if (!("outputDecryptedData" in this.mimeSvc)) {
       this.mimeSvc.onStopRequest(null, 0);
     }
-  }
+  },
 };
 
 function PgpMimeHandler() {
-
   EnigmailLog.DEBUG("pgpmimeHandler.js: PgpMimeHandler()\n"); // always log this one
-
 }
 
 PgpMimeHandler.prototype = {
   classDescription: "Enigmail JS Decryption Handler",
   classID: PGPMIME_JS_DECRYPTOR_CID,
   contractID: PGPMIME_JS_DECRYPTOR_CONTRACTID,
   QueryInterface: EnigmailCompat.generateQI([Ci.nsIStreamListener]),
-  inStream: Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream),
+  inStream: Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+    Ci.nsIScriptableInputStream
+  ),
 
-  onStartRequest: function(request, ctxt) {
+  onStartRequest(request, ctxt) {
     let mimeSvc = request.QueryInterface(Ci.nsIPgpMimeProxy);
     let ct = mimeSvc.contentType;
 
     let uri = null;
     if ("messageURI" in mimeSvc) {
       uri = mimeSvc.messageURI;
-    }
-    else {
+    } else {
       uri = ctxt;
     }
 
     if (!EnigmailCore.getService()) {
       // Ensure Enigmail is initialized
       if (ct.search(/application\/(x-)?pkcs7-signature/i) > 0) {
         return this.handleSmime(uri);
       }
@@ -176,119 +194,116 @@ PgpMimeHandler.prototype = {
     if (ct.search(/^multipart\/encrypted/i) === 0) {
       if (uri) {
         let u = uri.QueryInterface(Ci.nsIURI);
         gLastEncryptedUri = u.spec;
       }
       // PGP/MIME encrypted message
 
       cth = EnigmailMimeDecrypt.newPgpMimeHandler();
-    }
-    else if (ct.search(/^multipart\/signed/i) === 0) {
+    } else if (ct.search(/^multipart\/signed/i) === 0) {
       if (ct.search(/application\/pgp-signature/i) > 0) {
         // PGP/MIME signed message
         cth = EnigmailVerify.newVerifier();
-      }
-      else if (ct.search(/application\/(x-)?pkcs7-signature/i) > 0) {
+      } else if (ct.search(/application\/(x-)?pkcs7-signature/i) > 0) {
         let lastUriSpec = "";
         if (uri) {
           let u = uri.QueryInterface(Ci.nsIURI);
           lastUriSpec = u.spec;
         }
         // S/MIME signed message
         if (lastUriSpec !== gLastEncryptedUri && EnigmailVerify.lastMsgWindow) {
           // if message is displayed then handle like S/MIME message
           return this.handleSmime(uri);
         }
-        else {
-          // otherwise just make sure message body is returned
-          cth = EnigmailVerify.newVerifier("application/(x-)?pkcs7-signature");
-        }
+
+        // otherwise just make sure message body is returned
+        cth = EnigmailVerify.newVerifier("application/(x-)?pkcs7-signature");
       }
-    }
-    else if (ct.search(/application\/vnd.gnupg.wks/i) === 0) {
+    } else if (ct.search(/application\/vnd.gnupg.wks/i) === 0) {
       cth = EnigmailWksMimeHandler.newHandler();
     }
 
     if (!cth) {
-      EnigmailLog.ERROR("pgpmimeHandler.js: unknown protocol for content-type: " + ct + "\n");
+      EnigmailLog.ERROR(
+        "pgpmimeHandler.js: unknown protocol for content-type: " + ct + "\n"
+      );
       cth = new UnknownProtoHandler();
     }
 
     if (cth) {
       this.onDataAvailable = cth.onDataAvailable.bind(cth);
       this.onStopRequest = cth.onStopRequest.bind(cth);
       return cth.onStartRequest(request, uri);
     }
 
     return null;
   },
 
-  onDataAvailable: function(req, stream, offset, count) {},
+  onDataAvailable(req, stream, offset, count) {},
 
-  onStopRequest: function(request, status) {},
+  onStopRequest(request, status) {},
 
-  handleSmime: function(uri) {
+  handleSmime(uri) {
     this.contentHandler = throwErrors;
 
     if (uri) {
       uri = uri.QueryInterface(Ci.nsIURI);
     }
 
     let headerSink = EnigmailSingletons.messageReader;
     headerSink.handleSMimeMessage(uri);
   },
 
-  getMessengerWindow: function() {
-    let windowManager = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
+  getMessengerWindow() {
+    let windowManager = Services.wm;
 
     for (let win of windowManager.getEnumerator(null)) {
       if (win.location.href.search(/\/messenger.xhtml$/) > 0) {
         return win;
       }
     }
 
     return null;
-  }
+  },
 };
 
-
 class Factory {
   constructor(component) {
     this.component = component;
     this.register();
     Object.freeze(this);
   }
 
   createInstance(outer, iid) {
     if (outer) {
       throw Cr.NS_ERROR_NO_AGGREGATION;
     }
     return new this.component();
   }
 
   register() {
-    Cm.registerFactory(this.component.prototype.classID,
+    Cm.registerFactory(
+      this.component.prototype.classID,
       this.component.prototype.classDescription,
       this.component.prototype.contractID,
-      this);
+      this
+    );
   }
 
   unregister() {
     Cm.unregisterFactory(this.component.prototype.classID, this);
   }
 }
 
-
 var EnigmailPgpmimeHander = {
-  startup: function(reason) {
+  startup(reason) {
     try {
       this.factory = new Factory(PgpMimeHandler);
-    }
-    catch (ex) {}
+    } catch (ex) {}
   },
 
-  shutdown: function(reason) {
+  shutdown(reason) {
     if (this.factory) {
       this.factory.unregister();
     }
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/pipeConsole.jsm
+++ b/mail/extensions/openpgp/content/modules/pipeConsole.jsm
@@ -9,25 +9,25 @@
 
 var EXPORTED_SYMBOLS = ["EnigmailConsole"];
 
 const MAX_SIZE = 32768;
 var dataCache = "";
 var gotNewData = false;
 
 var EnigmailConsole = {
-  write: function(data) {
+  write(data) {
     dataCache += data;
     if (dataCache.length > MAX_SIZE) {
       dataCache = dataCache.substr(-MAX_SIZE, MAX_SIZE);
     }
     gotNewData = true;
   },
 
-  hasNewData: function() {
+  hasNewData() {
     return gotNewData;
   },
 
-  getData: function() {
+  getData() {
     gotNewData = false;
     return dataCache;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/prefs.jsm
+++ b/mail/extensions/openpgp/content/modules/prefs.jsm
@@ -3,128 +3,78 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailPrefs"];
 
-
-
-
-
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const {
-  Services
-} = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 const ENIGMAIL_PREFS_ROOT = "temp.openpgp.";
 
 const p = {
   service: null,
   branch: null,
   root: null,
-  defaultBranch: null
+  defaultBranch: null,
 };
 
 function initPrefService() {
   try {
-    p.service = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);
+    p.service = Services.prefs;
 
     p.root = p.service.getBranch(null);
     p.branch = p.service.getBranch(ENIGMAIL_PREFS_ROOT);
     p.defaultBranch = p.service.getDefaultBranch(null);
 
     try {
       if (p.branch.getCharPref("logDirectory")) {
         EnigmailLog.setLogLevel(5);
       }
-    }
-    catch (ex) {} // don't log anythign if accessing logDirectory fails
-  }
-  catch (ex) {
+    } catch (ex) {} // don't log anythign if accessing logDirectory fails
+  } catch (ex) {
     EnigmailLog.ERROR("prefs.jsm: Error in instantiating PrefService\n");
     EnigmailLog.ERROR(ex.toString());
   }
 }
 
-
-var gPrefs = {};
-
-/**
- * Load a preference default value
- * This function is called while loading defaultPrefs.js
- */
-function pref(key, val) {
-  gPrefs[key] = val;
-}
-
-/**
- * Load default preferences for bootstrapped addon
- */
-/* no longer necessary
-function setDefaultPrefs() {
-  EnigmailLog.DEBUG("prefs.jsm: setDefaultPrefs()\n");
-
-  Services.scriptloader.loadSubScript("chrome://openpgp/content/prefs/openpgp-prefs.js", {}, "UTF-8");
-
-  let branch = p.defaultBranch;
-  for (let key in gPrefs) {
-    try {
-      let val = gPrefs[key];
-      switch (typeof val) {
-        case "boolean":
-          branch.setBoolPref(key, val);
-          break;
-        case "number":
-          branch.setIntPref(key, val);
-          break;
-        case "string":
-          branch.setCharPref(key, val);
-          break;
-      }
-    }
-    catch(ex) {
-      EnigmailLog.ERROR(`prefs.jsm: setDefaultPrefs(${key}: ERROR ${ex.toString()}\n`);
-    }
-  }
-}
-*/
-
-
 var EnigmailPrefs = {
-  startup: function(reason) {
+  startup(reason) {
     try {
       initPrefService();
       //setDefaultPrefs();
-    }
-    catch (ex) {
-      EnigmailLog.ERROR("prefs.jsm: Error while loading default prefs: " + ex.message + "\n");
+    } catch (ex) {
+      EnigmailLog.ERROR(
+        "prefs.jsm: Error while loading default prefs: " + ex.message + "\n"
+      );
     }
   },
 
-  getPrefRoot: function() {
+  getPrefRoot() {
     if (!p.branch) {
       initPrefService();
     }
 
     return p.root;
   },
 
-  getPrefBranch: function() {
+  getPrefBranch() {
     if (!p.branch) {
       initPrefService();
     }
 
     return p.branch;
   },
 
-  getPref: function(prefName) {
+  getPref(prefName) {
     if (!p.branch) {
       initPrefService();
     }
 
     var prefValue = null;
     try {
       var prefType = p.branch.getPrefType(prefName);
       // Get pref value
@@ -137,34 +87,35 @@ var EnigmailPrefs = {
           break;
         case p.branch.PREF_STRING:
           prefValue = p.branch.getCharPref(prefName);
           break;
         default:
           prefValue = undefined;
           break;
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       // Failed to get pref value
-      EnigmailLog.ERROR("prefs.jsm: getPref: unknown prefName:" + prefName + " \n");
+      EnigmailLog.ERROR(
+        "prefs.jsm: getPref: unknown prefName:" + prefName + " \n"
+      );
     }
 
     return prefValue;
   },
 
   /**
    * Store a user preference.
    *
    * @param  String  prefName  An identifier.
    * @param  any     value     The value to be stored. Allowed types: Boolean OR Integer OR String.
    *
    * @return Boolean Was the value stored successfully?
    */
-  setPref: function(prefName, value) {
+  setPref(prefName, value) {
     EnigmailLog.DEBUG("prefs.jsm: setPref: " + prefName + ", " + value + "\n");
 
     if (!p.branch) {
       initPrefService();
     }
 
     // Discover the type of the preference, as stored in the user preferences.
     // If the preference identifier doesn't exist yet, it returns 0. In that
@@ -213,37 +164,36 @@ var EnigmailPrefs = {
     return retVal;
   },
 
   /**
    * Save the Mozilla preferences file (prefs.js)
    *
    * no return value
    */
-  savePrefs: function() {
+  savePrefs() {
     EnigmailLog.DEBUG("prefs.jsm: savePrefs\n");
     try {
       p.service.savePrefFile(null);
-    }
-    catch (ex) {}
+    } catch (ex) {}
   },
 
   /**
    * Compiles all Enigmail preferences into an object
    */
-  getAllPrefs: function() {
+  getAllPrefs() {
     EnigmailLog.DEBUG("prefs.js: getAllPrefs\n");
 
     var retObj = {
-      value: 0
+      value: 0,
     };
     var branch = this.getPrefBranch();
     var allPrefs = branch.getChildList("", retObj);
     var prefObj = {};
-    var nsIPB = Components.interfaces.nsIPrefBranch;
+    var nsIPB = Ci.nsIPrefBranch;
 
     for (var q in allPrefs) {
       var name = allPrefs[q];
 
       /*
        * agentPath is system-depend, configuredVersion build-depend and
        * advancedUser must be set in order to save the profile.
        */
@@ -272,51 +222,50 @@ var EnigmailPrefs = {
   /**
    * register a listener to listen to a change in the Enigmail preferences.
    *
    * @param prefName: String        - name of Enigmail preference
    * @param observerFunc: Function - callback function to be triggered
    *
    * @return Object: observer object (to be used to deregister the observer)
    */
-  registerPrefObserver: function(prefName, observerFunc) {
+  registerPrefObserver(prefName, observerFunc) {
     EnigmailLog.DEBUG("prefs.jsm: registerPrefObserver(" + prefName + ")\n");
     let branch = this.getPrefRoot();
 
     let observer = {
-      observe: function(aSubject, aTopic, aData) {
+      observe(aSubject, aTopic, aData) {
         try {
           if (String(aData) == ENIGMAIL_PREFS_ROOT + this.prefName) {
-            EnigmailLog.DEBUG("prefs.jsm: preference observed: " + aData + "\n");
+            EnigmailLog.DEBUG(
+              "prefs.jsm: preference observed: " + aData + "\n"
+            );
             observerFunc();
           }
-        }
-        catch (ex) {}
+        } catch (ex) {}
       },
 
-      prefName: prefName,
+      prefName,
 
-      QueryInterface: function(iid) {
-        if (iid.equals(Ci.nsIObserver) ||
-          iid.equals(Ci.nsISupportsWeakReference) ||
-          iid.equals(Ci.nsISupports))
-          return this;
-
-        throw Components.results.NS_NOINTERFACE;
-      }
+      QueryInterface: ChromeUtils.generateQI([
+        "nsIObserver",
+        "nsISupportsWeakReference",
+      ]),
     };
-    branch.addObserver(ENIGMAIL_PREFS_ROOT, observer, false);
+    branch.addObserver(ENIGMAIL_PREFS_ROOT, observer);
     return observer;
   },
 
   /**
    * de-register an observer created by registerPrefObserver().
    *
    * @param observer: Object - observer object returned by registerPrefObserver
    */
   unregisterPrefObserver(observer) {
-    EnigmailLog.DEBUG("prefs.jsm: unregisterPrefObserver(" + observer.prefName + ")\n");
+    EnigmailLog.DEBUG(
+      "prefs.jsm: unregisterPrefObserver(" + observer.prefName + ")\n"
+    );
 
     let branch = this.getPrefRoot();
 
     branch.removeObserver(ENIGMAIL_PREFS_ROOT, observer);
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/protocolHandler.jsm
+++ b/mail/extensions/openpgp/content/modules/protocolHandler.jsm
@@ -3,59 +3,81 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailProtocolHandler"];
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailURIs = ChromeUtils.import("chrome://openpgp/content/modules/uris.jsm").EnigmailURIs;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm").NetUtil;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const NS_ENIGMAILPROTOCOLHANDLER_CONTRACTID = "@mozilla.org/network/protocol;1?name=enigmail";
-const NS_ENIGMAILPROTOCOLHANDLER_CID = Components.ID("{847b3a11-7ab1-11d4-8f02-006008948af5}");
-const ASS_CONTRACTID = "@mozilla.org/appshell/appShellService;1";
-const WMEDIATOR_CONTRACTID = "@mozilla.org/appshell/window-mediator;1";
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailURIs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/uris.jsm"
+).EnigmailURIs;
+const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm")
+  .NetUtil;
+
+const NS_ENIGMAILPROTOCOLHANDLER_CONTRACTID =
+  "@mozilla.org/network/protocol;1?name=enigmail";
+const NS_ENIGMAILPROTOCOLHANDLER_CID = Components.ID(
+  "{847b3a11-7ab1-11d4-8f02-006008948af5}"
+);
 
 const nsIProtocolHandler = Ci.nsIProtocolHandler;
 
 var EC = EnigmailCore;
 
 const gDummyPKCS7 =
   'Content-Type: multipart/mixed;\r\n boundary="------------060503030402050102040303\r\n\r\nThis is a multi-part message in MIME format.\r\n--------------060503030402050102040303\r\nContent-Type: application/x-pkcs7-mime\r\nContent-Transfer-Encoding: 8bit\r\n\r\n\r\n--------------060503030402050102040303\r\nContent-Type: application/x-enigmail-dummy\r\nContent-Transfer-Encoding: 8bit\r\n\r\n\r\n--------------060503030402050102040303--\r\n';
 
-
 function EnigmailProtocolHandler() {}
 
 EnigmailProtocolHandler.prototype = {
   classDescription: "Enigmail Protocol Handler",
   classID: NS_ENIGMAILPROTOCOLHANDLER_CID,
   contractID: NS_ENIGMAILPROTOCOLHANDLER_CONTRACTID,
   scheme: "enigmail",
   defaultPort: -1,
-  protocolFlags: nsIProtocolHandler.URI_INHERITS_SECURITY_CONTEXT |
+  protocolFlags:
+    nsIProtocolHandler.URI_INHERITS_SECURITY_CONTEXT |
     nsIProtocolHandler.URI_LOADABLE_BY_ANYONE |
     nsIProtocolHandler.URI_NORELATIVE |
     nsIProtocolHandler.URI_NOAUTH |
     nsIProtocolHandler.URI_OPENING_EXECUTES_SCRIPT,
 
   QueryInterface: EnigmailCompat.generateQI([nsIProtocolHandler]),
 
-  newURI: function(aSpec, originCharset, aBaseURI) {
-    EnigmailLog.DEBUG("protocolHandler.jsm: EnigmailProtocolHandler.newURI: aSpec='" + aSpec + "'\n");
+  newURI(aSpec, originCharset, aBaseURI) {
+    EnigmailLog.DEBUG(
+      "protocolHandler.jsm: EnigmailProtocolHandler.newURI: aSpec='" +
+        aSpec +
+        "'\n"
+    );
 
     // cut of any parameters potentially added to the URI; these cannot be handled
-    if (aSpec.substr(0, 14) == "enigmail:dummy") aSpec = "enigmail:dummy";
+    if (aSpec.substr(0, 14) == "enigmail:dummy") {
+      aSpec = "enigmail:dummy";
+    }
 
     let uri;
 
     try {
       uri = Cc["@mozilla.org/network/simple-uri;1"].createInstance(Ci.nsIURI);
     } catch (x) {
       uri = NetUtil.newURI("data:text/plain,enigmail");
     }
@@ -71,122 +93,149 @@ EnigmailProtocolHandler.prototype = {
         uri.scheme = "enigmail";
         if (i >= 0) {
           uri.query = aSpec.substr(i + 1);
           uri.pathQueryRef = aSpec.substr(0, i);
         } else {
           uri.pathQueryRef = aSpec;
         }
       } catch (ex) {
-        uri = uri.mutate().setScheme("enigmail").finalize();
+        uri = uri
+          .mutate()
+          .setScheme("enigmail")
+          .finalize();
         if (i >= 0) {
-          uri = uri.mutate().setQuery(aSpec.substr(i + 1)).finalize();
-          uri = uri.mutate().setPathQueryRef(aSpec.substr(0, i)).finalize();
+          uri = uri
+            .mutate()
+            .setQuery(aSpec.substr(i + 1))
+            .finalize();
+          uri = uri
+            .mutate()
+            .setPathQueryRef(aSpec.substr(0, i))
+            .finalize();
         } else {
-          uri = uri.mutate().setPathQueryRef(aSpec).finalize();
+          uri = uri
+            .mutate()
+            .setPathQueryRef(aSpec)
+            .finalize();
         }
       }
-
     }
 
     return uri;
   },
 
-  newChannel: function(aURI, loadInfo) {
-    EnigmailLog.DEBUG("protocolHandler.jsm: EnigmailProtocolHandler.newChannel: URI='" + aURI.spec + "'\n");
+  newChannel(aURI, loadInfo) {
+    EnigmailLog.DEBUG(
+      "protocolHandler.jsm: EnigmailProtocolHandler.newChannel: URI='" +
+        aURI.spec +
+        "'\n"
+    );
 
     var messageId = EnigmailData.extractMessageId(aURI.spec);
     var mimeMessageId = EnigmailData.extractMimeMessageId(aURI.spec);
     var contentType, contentCharset, contentData;
 
     if (messageId) {
       // Handle enigmail:message/...
 
       if (!EC.getEnigmailService()) {
-        throw Components.results.NS_ERROR_FAILURE;
+        throw Cr.NS_ERROR_FAILURE;
       }
 
       if (EnigmailURIs.getMessageURI(messageId)) {
         var messageUriObj = EnigmailURIs.getMessageURI(messageId);
 
         contentType = messageUriObj.contentType;
         contentCharset = messageUriObj.contentCharset;
         contentData = messageUriObj.contentData;
 
-        EnigmailLog.DEBUG("protocolHandler.jsm: EnigmailProtocolHandler.newChannel: messageURL=" + messageUriObj.originalUrl + ", content length=" + contentData.length + ", " + contentType + ", " +
-          contentCharset + "\n");
+        EnigmailLog.DEBUG(
+          "protocolHandler.jsm: EnigmailProtocolHandler.newChannel: messageURL=" +
+            messageUriObj.originalUrl +
+            ", content length=" +
+            contentData.length +
+            ", " +
+            contentType +
+            ", " +
+            contentCharset +
+            "\n"
+        );
 
         // do NOT delete the messageUriObj now from the list, this will be done once the message is unloaded (fix for bug 9730).
-
       } else if (mimeMessageId) {
         this.handleMimeMessage(mimeMessageId);
       } else {
-
         contentType = "text/plain";
         contentCharset = "";
         contentData = "Enigmail error: invalid URI " + aURI.spec;
       }
 
-      let channel = EnigmailStreams.newStringChannel(aURI, contentType, "UTF-8", contentData, loadInfo);
-
+      let channel = EnigmailStreams.newStringChannel(
+        aURI,
+        contentType,
+        "UTF-8",
+        contentData,
+        loadInfo
+      );
 
       return channel;
     }
 
     if (aURI.spec == aURI.scheme + ":dummy") {
       // Dummy PKCS7 content (to access mimeEncryptedClass)
-      return EnigmailStreams.newStringChannel(aURI, "message/rfc822", "", gDummyPKCS7, loadInfo);
+      return EnigmailStreams.newStringChannel(
+        aURI,
+        "message/rfc822",
+        "",
+        gDummyPKCS7,
+        loadInfo
+      );
     }
 
-    var winName, spec;
+    var spec;
     if (aURI.spec == "about:" + aURI.scheme) {
       // About Enigmail
-      //            winName = "about:"+enigmail;
-      winName = "about:enigmail";
       spec = "chrome://openpgp/content/ui/enigmailAbout.xhtml";
-
     } else if (aURI.spec == aURI.scheme + ":console") {
       // Display enigmail console messages
-      winName = "enigmail:console";
       spec = "chrome://openpgp/content/ui/enigmailConsole.xhtml";
-
     } else if (aURI.spec == aURI.scheme + ":keygen") {
       // Display enigmail key generation console
-      winName = "enigmail:keygen";
       spec = "chrome://openpgp/content/ui/enigmailKeygen.xhtml";
-
     } else {
       // Display Enigmail about page
-      winName = "about:enigmail";
       spec = "chrome://openpgp/content/ui/enigmailAbout.xhtml";
     }
 
-    var windowManager = Cc[WMEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+    var windowManager = Services.wm;
 
     var recentWin = null;
     for (let win of windowManager.getEnumerator(null)) {
       if (win.location.href == spec) {
         recentWin = win;
       }
     }
 
     if (recentWin) {
       recentWin.focus();
     } else {
-      var appShellSvc = Cc[ASS_CONTRACTID].getService(Ci.nsIAppShellService);
+      var appShellSvc = Services.appShell;
       var domWin = appShellSvc.hiddenDOMWindow;
 
       domWin.open(spec, "_blank", "chrome,menubar,toolbar,resizable");
     }
 
-    throw Components.results.NS_ERROR_FAILURE;
+    throw Cr.NS_ERROR_FAILURE;
   },
 
-  handleMimeMessage: function(messageId) {
+  handleMimeMessage(messageId) {
     //        EnigmailLog.DEBUG("protocolHandler.jsm: EnigmailProtocolHandler.handleMimeMessage: messageURL="+messageUriObj.originalUrl+", content length="+contentData.length+", "+contentType+", "+contentCharset+"\n");
-    EnigmailLog.DEBUG("protocolHandler.jsm: EnigmailProtocolHandler.handleMimeMessage: messageURL=, content length=, , \n");
+    EnigmailLog.DEBUG(
+      "protocolHandler.jsm: EnigmailProtocolHandler.handleMimeMessage: messageURL=, content length=, , \n"
+    );
   },
 
-  allowPort: function(port, scheme) {
+  allowPort(port, scheme) {
     // non-standard ports are not allowed
     return false;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/rng.jsm
+++ b/mail/extensions/openpgp/content/modules/rng.jsm
@@ -3,34 +3,92 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailRNG"];
 
-Components.utils.importGlobalProperties(["crypto"]);
+Cu.importGlobalProperties(["crypto"]);
 
 /**
  * Create a string of random characters of the set A-Z a-z 0-9 with numChars length,
  * using the browser crypto API that gets cryptographically strong random values
  *
  * @param numChar: Number - the length of the string to return
  *
  * @return String
  */
 function generateRandomString(numChars) {
-
   // Map of characters that are allowed to be returned
-  const charMap = new Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
-    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
-    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
-    "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
-    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
+  const charMap = [
+    "A",
+    "B",
+    "C",
+    "D",
+    "E",
+    "F",
+    "G",
+    "H",
+    "I",
+    "J",
+    "K",
+    "L",
+    "M",
+    "N",
+    "O",
+    "P",
+    "Q",
+    "R",
+    "S",
+    "T",
+    "U",
+    "V",
+    "W",
+    "X",
+    "Y",
+    "Z",
+    "a",
+    "b",
+    "c",
+    "d",
+    "e",
+    "f",
+    "g",
+    "h",
+    "i",
+    "j",
+    "k",
+    "l",
+    "m",
+    "n",
+    "o",
+    "p",
+    "q",
+    "r",
+    "s",
+    "t",
+    "u",
+    "v",
+    "w",
+    "x",
+    "y",
+    "z",
+    "0",
+    "1",
+    "2",
+    "3",
+    "4",
+    "5",
+    "6",
+    "7",
+    "8",
+    "9",
+  ];
 
   const charMapLength = charMap.length; // 62 for the set A-Z a-z 0-9
 
   let randNumArray = new Uint16Array(numChars);
   crypto.getRandomValues(randNumArray);
 
   let randomString = "";
 
@@ -40,24 +98,23 @@ function generateRandomString(numChars) 
     let modulo = randNumArray[i] % charMapLength;
 
     randomString += charMap[modulo];
   }
 
   return randomString;
 }
 
-
 /**
  * Generates a random UInt32 for use in randomising key selection and wait times between refreshing keys.
  *
  * @return random UInt32
  */
 function generateRandomUint32() {
   let randomNumber = new Uint32Array(1);
   crypto.getRandomValues(randomNumber);
   return randomNumber[0];
 }
 
 var EnigmailRNG = {
-  generateRandomUint32: generateRandomUint32,
-  generateRandomString: generateRandomString
+  generateRandomUint32,
+  generateRandomString,
 };
--- a/mail/extensions/openpgp/content/modules/rnp.jsm
+++ b/mail/extensions/openpgp/content/modules/rnp.jsm
@@ -49,24 +49,24 @@ var RNP = {
     }
 
     if (!RNP.libLoaded) {
       console.log("failed to load RNP library");
     }
   },
 
   addKeyAttributes(handle, meta, keyObj, is_subkey, forListing) {
-    let have_secret = new ctypes.bool;
-    let key_id = new ctypes.char.ptr;
-    let fingerprint = new ctypes.char.ptr;
-    let algo = new ctypes.char.ptr;
-    let bits = new ctypes.uint32_t;
-    let key_creation = new ctypes.uint32_t;
-    let key_expiration = new ctypes.uint32_t;
-    let allowed = new ctypes.bool;
+    let have_secret = new ctypes.bool();
+    let key_id = new ctypes.char.ptr();
+    let fingerprint = new ctypes.char.ptr();
+    let algo = new ctypes.char.ptr();
+    let bits = new ctypes.uint32_t();
+    let key_creation = new ctypes.uint32_t();
+    let key_expiration = new ctypes.uint32_t();
+    let allowed = new ctypes.bool();
 
     if (RNPLib.rnp_key_have_secret(handle, have_secret.address())) {
       throw new Error("rnp_key_have_secret failed");
     }
 
     keyObj.secretAvailable = have_secret.value;
 
     if (is_subkey) {
@@ -87,17 +87,17 @@ var RNP = {
       throw new Error("rnp_key_get_fprint failed");
     }
     keyObj.fpr = fingerprint.readString();
 
     if (RNPLib.rnp_key_get_alg(handle, algo.address())) {
       throw new Error("rnp_key_get_alg failed");
     }
     keyObj.algoSym = algo.readString();
-    
+
     if (RNPLib.rnp_key_get_bits(handle, bits.address())) {
       throw new Error("rnp_key_get_bits failed");
     }
     keyObj.keySize = bits.value;
 
     if (RNPLib.rnp_key_get_creation(handle, key_creation.address())) {
       throw new Error("rnp_key_get_creation failed");
     }
@@ -131,70 +131,72 @@ var RNP = {
     }
     if (RNPLib.rnp_key_allows_usage(handle, str_certify, allowed.address())) {
       throw new Error("rnp_key_allows_usage failed");
     }
     if (allowed.value) {
       keyObj.keyUseFor += "c";
       meta.c = true;
     }
-    if (RNPLib.rnp_key_allows_usage(handle, str_authenticate, allowed.address())) {
+    if (
+      RNPLib.rnp_key_allows_usage(handle, str_authenticate, allowed.address())
+    ) {
       throw new Error("rnp_key_allows_usage failed");
     }
     if (allowed.value) {
       keyObj.keyUseFor += "a";
       meta.a = true;
     }
   },
-  
+
   getKeys(onlyKeys = null) {
     return this.getKeysFromFFI(RNPLib.ffi, false, onlyKeys);
   },
 
-  /* Some consumers want a different listing of keys, and expect 
+  /* Some consumers want a different listing of keys, and expect
    * slightly different attribute names...
    * If forListing is true, we'll set those additional attributes. */
   getKeysFromFFI(ffi, forListing, onlyKeys = null) {
     let keys = [];
     let rv;
 
-    let iter = new RNPLib.rnp_identifier_iterator_t;
+    let iter = new RNPLib.rnp_identifier_iterator_t();
     let grip = new ctypes.char.ptr();
 
     rv = RNPLib.rnp_identifier_iterator_create(ffi, iter.address(), "grip");
     if (rv) {
       return null;
     }
-    
+
     let meta = {
       a: false,
       s: false,
       c: false,
       e: false,
     };
 
     while (!RNPLib.rnp_identifier_iterator_next(iter, grip.address())) {
       if (grip.isNull()) {
         break;
       }
 
       let have_handle = false;
-      let handle = new RNPLib.rnp_key_handle_t;
+      let handle = new RNPLib.rnp_key_handle_t();
       let keyObj = {};
 
       keyObj.ownerTrust = null;
       keyObj.userId = null;
       keyObj.userIds = [];
       keyObj.subKeys = [];
       keyObj.photoAvailable = false;
 
       try {
-        let is_subkey = new ctypes.bool;
-        let sub_count = new ctypes.size_t;
-        let uid_count = new ctypes.size_t;
+        let is_subkey = new ctypes.bool();
+        let sub_count = new ctypes.size_t();
+        let uid_count = new ctypes.size_t();
 
         if (RNPLib.rnp_locate_key(ffi, "grip", grip, handle.address())) {
           throw new Error("rnp_locate_key failed");
         }
         have_handle = true;
         if (RNPLib.rnp_key_is_sub(handle, is_subkey.address())) {
           throw new Error("rnp_key_is_sub failed");
         }
@@ -207,17 +209,17 @@ var RNP = {
           if (!primary_grip.isNull()) {
             RNPLib.rnp_buffer_destroy(primary_grip);
             continue;
           }
         }
 
         this.addKeyAttributes(handle, meta, keyObj, false, forListing);
 
-        let key_revoked = new ctypes.bool;
+        let key_revoked = new ctypes.bool();
         if (RNPLib.rnp_key_is_revoked(handle, key_revoked.address())) {
           throw new Error("rnp_key_is_revoked failed");
         }
 
         if (key_revoked.value) {
           keyObj.keyTrust = "r";
           if (forListing) {
             keyObj.revoke = true;
@@ -227,81 +229,83 @@ var RNP = {
         } else {
           keyObj.keyTrust = "o";
         }
 
         /* The remaining actions are done for primary keys, only. */
         if (is_subkey.value) {
           continue;
         }
-        
+
         let primary_uid_set = false;
 
         if (RNPLib.rnp_key_get_uid_count(handle, uid_count.address())) {
           throw new Error("rnp_key_get_uid_count failed");
         }
         console.debug("rnp_key_get_uid_count: " + uid_count.value);
         for (let i = 0; i < uid_count.value; i++) {
-          let uid_handle = new RNPLib.rnp_uid_handle_t;
-          let is_revoked = new ctypes.bool;
+          let uid_handle = new RNPLib.rnp_uid_handle_t();
+          let is_revoked = new ctypes.bool();
 
-          if (RNPLib.rnp_key_get_uid_handle_at(handle, i, uid_handle.address())) {
+          if (
+            RNPLib.rnp_key_get_uid_handle_at(handle, i, uid_handle.address())
+          ) {
             throw new Error("rnp_key_get_uid_handle_at failed");
           }
 
           if (RNPLib.rnp_uid_is_revoked(uid_handle, is_revoked.address())) {
             throw new Error("rnp_uid_is_revoked failed");
           }
 
           if (!is_revoked.value) {
-            let uid_str = new ctypes.char.ptr;
+            let uid_str = new ctypes.char.ptr();
             if (RNPLib.rnp_key_get_uid_at(handle, i, uid_str.address())) {
               throw new Error("rnp_key_get_uid_at failed");
             }
-            
+
             if (!primary_uid_set) {
               keyObj.userId = uid_str.readString();
               if (forListing) {
                 keyObj.name = keyObj.userId;
               }
               primary_uid_set = true;
             }
 
             let uidObj = {};
             uidObj.userId = uid_str.readString();
             uidObj.type = "uid";
             uidObj.keyTrust = keyObj.keyTrust;
-            uidObj.uidFpr = "??fpr??"
-            
+            uidObj.uidFpr = "??fpr??";
+
             keyObj.userIds.push(uidObj);
-            
+
             RNPLib.rnp_buffer_destroy(uid_str);
           }
 
           RNPLib.rnp_uid_handle_destroy(uid_handle);
         }
 
         if (RNPLib.rnp_key_get_subkey_count(handle, sub_count.address())) {
           throw new Error("rnp_key_get_subkey_count failed");
         }
         console.debug("rnp_key_get_subkey_count: " + sub_count.value);
         for (let i = 0; i < sub_count.value; i++) {
-          let sub_handle = new RNPLib.rnp_key_handle_t;
+          let sub_handle = new RNPLib.rnp_key_handle_t();
           if (RNPLib.rnp_key_get_subkey_at(handle, i, sub_handle.address())) {
-              throw new Error("rnp_key_get_subkey_at failed");
+            throw new Error("rnp_key_get_subkey_at failed");
           }
 
           let subKeyObj = {};
           subKeyObj.keyTrust = keyObj.keyTrust;
           this.addKeyAttributes(sub_handle, meta, subKeyObj, true, forListing);
           keyObj.subKeys.push(subKeyObj);
 
           RNPLib.rnp_key_handle_destroy(sub_handle);
         }
-        
+
         if (meta.s) {
           keyObj.keyUseFor += "S";
         }
         if (meta.a) {
           keyObj.keyUseFor += "A";
         }
         if (meta.c) {
           keyObj.keyUseFor += "C";
@@ -316,23 +320,23 @@ var RNP = {
           RNPLib.rnp_key_handle_destroy(handle);
         }
       }
 
       keys.push(keyObj);
     }
 
     RNPLib.rnp_identifier_iterator_destroy(iter);
-    
+
     console.log(keys);
     return keys;
   },
 
   decrypt(encrypted, options) {
-    let input_from_memory = new RNPLib.rnp_input_t;
+    let input_from_memory = new RNPLib.rnp_input_t();
 
     /*
     let uint8_array_type = ctypes.ArrayType(ctypes.uint8_t);
     let encrypted_array = uint8_array_type(encrypted.length + 1);
     
     for (let i = 0; i < encrypted.length; i++) {
       encrypted_array[i] = encrypted.charCodeAt(i);
     }
@@ -349,17 +353,17 @@ var RNP = {
       input_from_memory.address(),
       encrypted_array,
       encrypted.length,
       false
     );
 
     let max_out = encrypted.length * 10;
 
-    let output_to_memory = new RNPLib.rnp_output_t;
+    let output_to_memory = new RNPLib.rnp_output_t();
     RNPLib.rnp_output_to_memory(output_to_memory.address(), max_out);
 
     let result = {};
     result.decryptedData = "";
     result.statusFlags = 0;
 
     result.exitCode = RNPLib.rnp_decrypt(
       RNPLib.ffi,
@@ -399,19 +403,18 @@ var RNP = {
       result.statusFlags |= EnigmailConstants.DECRYPTION_FAILED;
     }
 
     RNPLib.rnp_input_destroy(input_from_memory);
     RNPLib.rnp_output_destroy(output_to_memory);
 
     return result;
   },
-  
+
   genKey(userId, keyType, keyBits, expiryDays, passphrase) {
-    
     let newKeyId = "";
 
     let primaryKeyType;
     let primaryKeyBits = 0;
     let subKeyType;
     let subKeyBits = 0;
     let primaryKeyCurve = null;
     let subKeyCurve = null;
@@ -420,314 +423,352 @@ var RNP = {
     if (keyType == "RSA") {
       primaryKeyType = subKeyType = "rsa";
       primaryKeyBits = subKeyBits = keyBits;
     } else if (keyType == "ECC") {
       primaryKeyType = "eddsa";
       subKeyType = "ecdh";
       subKeyCurve = "Curve25519";
     } else {
-      return;
+      return null;
     }
 
     if (expiryDays != 0) {
-      expireSeconds = expiryDays*24*60*60;
+      expireSeconds = expiryDays * 24 * 60 * 60;
     }
 
-    let genOp = new RNPLib.rnp_op_generate_t;
-    if (RNPLib.rnp_op_generate_create(genOp.address(), RNPLib.ffi, primaryKeyType)) {
+    let genOp = new RNPLib.rnp_op_generate_t();
+    if (
+      RNPLib.rnp_op_generate_create(genOp.address(), RNPLib.ffi, primaryKeyType)
+    ) {
       throw new Error("rnp_op_generate_create primary failed");
     }
 
     if (RNPLib.rnp_op_generate_set_userid(genOp, userId)) {
       throw new Error("rnp_op_generate_set_userid failed");
     }
-    
+
     if (passphrase != null && passphrase.length != 0) {
       if (RNPLib.rnp_op_generate_set_protection_password(genOp, passphrase)) {
         throw new Error("rnp_op_generate_set_protection_password failed");
       }
     }
-    
+
     if (primaryKeyBits != 0) {
       if (RNPLib.rnp_op_generate_set_bits(genOp, primaryKeyBits)) {
         throw new Error("rnp_op_generate_set_bits primary failed");
       }
     }
-    
+
     if (primaryKeyCurve != null) {
       if (RNPLib.rnp_op_generate_set_curve(genOp, primaryKeyCurve)) {
         throw new Error("rnp_op_generate_set_curve primary failed");
       }
     }
-    
+
     if (expireSeconds != 0) {
       if (RNPLib.rnp_op_generate_set_expiration(genOp, expireSeconds)) {
         throw new Error("rnp_op_generate_set_expiration primary failed");
       }
     }
-    
+
     if (RNPLib.rnp_op_generate_execute(genOp)) {
       throw new Error("rnp_op_generate_execute primary failed");
     }
-    
-    let primaryKey = new RNPLib.rnp_key_handle_t;
+
+    let primaryKey = new RNPLib.rnp_key_handle_t();
     if (RNPLib.rnp_op_generate_get_key(genOp, primaryKey.address())) {
       throw new Error("rnp_op_generate_get_key primary failed");
     }
 
     RNPLib.rnp_op_generate_destroy(genOp);
 
-    let ctypes_key_id = new ctypes.char.ptr;
+    let ctypes_key_id = new ctypes.char.ptr();
     if (RNPLib.rnp_key_get_keyid(primaryKey, ctypes_key_id.address())) {
       throw new Error("rnp_key_get_keyid failed");
     }
     newKeyId = ctypes_key_id.readString();
-    
-    if (RNPLib.rnp_op_generate_subkey_create(genOp.address(), RNPLib.ffi, primaryKey, subKeyType)) {
+
+    if (
+      RNPLib.rnp_op_generate_subkey_create(
+        genOp.address(),
+        RNPLib.ffi,
+        primaryKey,
+        subKeyType
+      )
+    ) {
       throw new Error("rnp_op_generate_subkey_create primary failed");
     }
 
     if (passphrase != null && passphrase.length != 0) {
       if (RNPLib.rnp_op_generate_set_protection_password(genOp, passphrase)) {
         throw new Error("rnp_op_generate_set_protection_password failed");
       }
     }
 
     if (subKeyBits != 0) {
       if (RNPLib.rnp_op_generate_set_bits(genOp, subKeyBits)) {
         throw new Error("rnp_op_generate_set_bits sub failed");
       }
     }
-    
+
     if (subKeyCurve != null) {
       if (RNPLib.rnp_op_generate_set_curve(genOp, subKeyCurve)) {
         throw new Error("rnp_op_generate_set_curve sub failed");
       }
     }
-    
+
     if (expireSeconds != 0) {
       if (RNPLib.rnp_op_generate_set_expiration(genOp, expireSeconds)) {
         throw new Error("rnp_op_generate_set_expiration sub failed");
       }
     }
 
+    let lockFailure = false;
     try {
       if (passphrase != null && passphrase.length != 0) {
         if (RNPLib.rnp_key_unlock(primaryKey, passphrase)) {
           throw new Error("rnp_key_unlock failed");
         }
       }
 
       if (RNPLib.rnp_op_generate_execute(genOp)) {
         throw new Error("rnp_op_generate_execute sub failed");
       }
     } finally {
       if (RNPLib.rnp_key_lock(primaryKey)) {
-        throw new Error("rnp_key_lock failed");
+        lockFailure = true;
       }
     }
+    if (lockFailure) {
+      throw new Error("rnp_key_lock failed");
+    }
 
     RNPLib.rnp_op_generate_destroy(genOp);
-    
+
     return newKeyId;
   },
 
   saveKeyRings() {
     RNPLib.saveKeys();
   },
-  
+
   importToFFI(ffi, keyBlockStr) {
-    let input_from_memory = new RNPLib.rnp_input_t;
+    let input_from_memory = new RNPLib.rnp_input_t();
 
     var tmp_array = ctypes.char.array()(keyBlockStr);
     var key_array = ctypes.cast(
       tmp_array,
       ctypes.uint8_t.array(keyBlockStr.length)
     );
 
     RNPLib.rnp_input_from_memory(
       input_from_memory.address(),
       key_array,
       keyBlockStr.length,
       false
     );
 
     let jsonInfo = new ctypes.char.ptr();
-    
-    let rv = RNPLib.rnp_import_keys(ffi, input_from_memory,
-                                    RNPLib.RNP_LOAD_SAVE_PUBLIC_KEYS,
-                                    jsonInfo.address());
 
-    // TODO: parse jsonInfo and return a list of keys, 
+    let rv = RNPLib.rnp_import_keys(
+      ffi,
+      input_from_memory,
+      RNPLib.RNP_LOAD_SAVE_PUBLIC_KEYS,
+      jsonInfo.address()
+    );
+
+    // TODO: parse jsonInfo and return a list of keys,
     // as seen in keyRing.importKeyAsync.
     // (should prevent the incorrect popup "no keys imported".)
 
-    console.debug("result key listing, rv= %s, result= %s", rv, jsonInfo.readString());
+    console.debug(
+      "result key listing, rv= %s, result= %s",
+      rv,
+      jsonInfo.readString()
+    );
 
     RNPLib.rnp_buffer_destroy(jsonInfo);
     RNPLib.rnp_input_destroy(input_from_memory);
-    
+
     return null;
   },
 
   getKeyListFromKeyBlock(keyBlockStr) {
     // Create a separate, temporary RNP storage area (FFI),
     // import the key block into it, then get the listing.
 
     console.debug("trying to get key listing for this data: " + keyBlockStr);
 
-    let tempFFI = new RNPLib.rnp_ffi_t;
+    let tempFFI = new RNPLib.rnp_ffi_t();
     if (RNPLib.rnp_ffi_create(tempFFI.address(), "GPG", "GPG")) {
       throw new Error("Couldn't initialize librnp.");
     }
-    
+
     this.importToFFI(tempFFI, keyBlockStr);
 
     let keys = this.getKeysFromFFI(tempFFI, true);
 
     console.debug("result key array: %o", keys);
 
     RNPLib.rnp_ffi_destroy(tempFFI);
     return keys;
   },
-  
+
   importKeyBlock(keyBlockStr) {
     return this.importToFFI(RNPLib.ffi, keyBlockStr);
   },
 
   deleteKey(keyFingerprint, deleteSecret) {
     console.debug("deleting key with fingerprint: " + keyFingerprint);
 
-    let handle = new RNPLib.rnp_key_handle_t;
-    if (RNPLib.rnp_locate_key(RNPLib.ffi, "fingerprint", keyFingerprint, handle.address())) {
+    let handle = new RNPLib.rnp_key_handle_t();
+    if (
+      RNPLib.rnp_locate_key(
+        RNPLib.ffi,
+        "fingerprint",
+        keyFingerprint,
+        handle.address()
+      )
+    ) {
       throw new Error("rnp_locate_key failed");
     }
 
     let flags = RNPLib.RNP_KEY_REMOVE_PUBLIC;
     if (deleteSecret) {
       flags |= RNPLib.RNP_KEY_REMOVE_SECRET;
     }
-    
+
     if (RNPLib.rnp_key_remove(handle, flags)) {
-      throw ("rnp_key_remove failed");
+      throw new Error("rnp_key_remove failed");
     }
 
     RNPLib.rnp_key_handle_destroy(handle);
     this.saveKeyRings();
   },
 
   getKeyHandleByIdentifier(id) {
     console.debug("getKeyHandleByIdentifier searching for: " + id);
     let key = null;
-    
+
     if (id.startsWith("<")) {
       //throw new Error("search by email address not yet implemented: " + id);
       if (!id.endsWith(">")) {
-        throw new Error("if search identifier starts with < then it must end with > : " + id);
+        throw new Error(
+          "if search identifier starts with < then it must end with > : " + id
+        );
       }
       key = this.findKeyByEmail(id);
     } else {
       if (!id.startsWith("0x")) {
         throw new Error("unexpected identifier " + id);
       } else {
         // remove 0x
         id = id.substring(2);
       }
 
       let type = null;
       if (id.length == 16) {
         type = "keyid";
       } else if (id.length == 40 || id.length == 32) {
         type = "fingerprint";
       } else {
-        throw new Error("key/fingerprint identifier of unexpected length: " + id);
+        throw new Error(
+          "key/fingerprint identifier of unexpected length: " + id
+        );
       }
 
-      key = new RNPLib.rnp_key_handle_t;
+      key = new RNPLib.rnp_key_handle_t();
       if (RNPLib.rnp_locate_key(RNPLib.ffi, type, id, key.address())) {
         throw new Error("rnp_locate_key failed, " + type + ", " + id);
       }
     }
-    
+
     if (key.isNull()) {
       console.debug("getKeyHandleByIdentifier nothing found");
     } else {
       console.debug("getKeyHandleByIdentifier found!");
-      let is_subkey = new ctypes.bool;
+      let is_subkey = new ctypes.bool();
       let res = RNPLib.rnp_key_is_sub(key, is_subkey.address());
       if (res) {
         throw new Error("rnp_key_is_sub failed: " + res);
       }
       console.debug("is_primary? " + !is_subkey.value);
     }
-    
+
     return key;
   },
-  
+
   isKeyUsableFor(key, usage) {
-    let allowed = new ctypes.bool;
+    let allowed = new ctypes.bool();
     if (RNPLib.rnp_key_allows_usage(key, usage, allowed.address())) {
       throw new Error("rnp_key_allows_usage failed");
     }
     return allowed.value;
   },
-  
+
   getSuitableSubkey(primary, usage) {
     let found_handle = null;
-    let sub_count = new ctypes.size_t;
+    let sub_count = new ctypes.size_t();
     if (RNPLib.rnp_key_get_subkey_count(primary, sub_count.address())) {
       throw new Error("rnp_key_get_subkey_count failed");
     }
     for (let i = 0; i < sub_count.value; i++) {
-      let sub_handle = new RNPLib.rnp_key_handle_t;
+      let sub_handle = new RNPLib.rnp_key_handle_t();
       if (RNPLib.rnp_key_get_subkey_at(primary, i, sub_handle.address())) {
-          throw new Error("rnp_key_get_subkey_at failed");
+        throw new Error("rnp_key_get_subkey_at failed");
       }
-      let expiration = new ctypes.uint32_t;
+      let expiration = new ctypes.uint32_t();
       if (RNPLib.rnp_key_get_expiration(sub_handle, expiration.address())) {
         throw new Error("rnp_key_get_expiration failed");
       }
       let skip = false;
       if (expiration.value != 0) {
-        let now_seconds = Math.floor(Date.now()/1000);
-        let creation = new ctypes.uint32_t;
+        let now_seconds = Math.floor(Date.now() / 1000);
+        let creation = new ctypes.uint32_t();
         if (RNPLib.rnp_key_get_creation(sub_handle, creation.address())) {
           throw new Error("rnp_key_get_expiration failed");
         }
         let expiration_seconds = creation.value + expiration.value;
-        console.debug("now: " + now_seconds + " vs. subkey creation+expiration in seconds: " + expiration_seconds);
+        console.debug(
+          "now: " +
+            now_seconds +
+            " vs. subkey creation+expiration in seconds: " +
+            expiration_seconds
+        );
         if (now_seconds > expiration_seconds) {
           console.debug("skipping expired subkey");
           skip = true;
         }
       }
       if (!skip) {
-        let key_revoked = new ctypes.bool;
+        let key_revoked = new ctypes.bool();
         if (RNPLib.rnp_key_is_revoked(sub_handle, key_revoked.address())) {
           console.debug("skipping revoked subkey");
           skip = true;
         }
       }
       if (!skip) {
         if (!this.isKeyUsableFor(sub_handle, usage)) {
           console.debug("skipping subkey not usable for request");
           skip = true;
         }
       }
       if (skip) {
         RNPLib.rnp_key_handle_destroy(sub_handle);
       } else {
         found_handle = sub_handle;
 
-        let fingerprint = new ctypes.char.ptr;
+        let fingerprint = new ctypes.char.ptr();
         if (RNPLib.rnp_key_get_fprint(found_handle, fingerprint.address())) {
           throw new Error("rnp_key_get_fprint failed");
         }
-        console.debug("found suitable subkey, fingerprint: " + fingerprint.readString());
+        console.debug(
+          "found suitable subkey, fingerprint: " + fingerprint.readString()
+        );
         break;
       }
     }
 
     return found_handle;
   },
 
   addSuitableEncryptKey(key, op) {
@@ -741,68 +782,93 @@ var RNP = {
       use_sub = this.getSuitableSubkey(key, str_encrypt);
       if (!use_sub) {
         throw new Error("no suitable subkey found for " + str_encrypt);
       } else {
         console.debug("addSuitableEncryptKey using subkey");
       }
     }
 
-    if (RNPLib.rnp_op_encrypt_add_recipient(op, (use_sub != null) ? use_sub : key)) {
+    if (
+      RNPLib.rnp_op_encrypt_add_recipient(op, use_sub != null ? use_sub : key)
+    ) {
       throw new Error("rnp_op_encrypt_add_recipient sender failed");
     }
     if (use_sub) {
       RNPLib.rnp_key_handle_destroy(use_sub);
     }
   },
 
   encryptAndOrSign(plaintext, args, resultStatus) {
     resultStatus.exitCode = -1;
     resultStatus.statusFlags = 0;
     resultStatus.statusMsg = "";
     resultStatus.errorMsg = "";
 
-    console.debug(`encryptAndOrSign, plaintext (length=${plaintext.length}): ${plaintext}`);
+    console.debug(
+      `encryptAndOrSign, plaintext (length=${plaintext.length}): ${plaintext}`
+    );
 
     var tmp_array = ctypes.char.array()(plaintext);
     var plaintext_array = ctypes.cast(
       tmp_array,
       ctypes.uint8_t.array(plaintext.length)
     );
 
-    let input = new RNPLib.rnp_input_t;
-    if (RNPLib.rnp_input_from_memory(input.address(), plaintext_array,
-          plaintext.length, false)) {
+    let input = new RNPLib.rnp_input_t();
+    if (
+      RNPLib.rnp_input_from_memory(
+        input.address(),
+        plaintext_array,
+        plaintext.length,
+        false
+      )
+    ) {
       throw new Error("rnp_input_from_memory failed");
     }
 
-    let output = new RNPLib.rnp_output_t;
+    let output = new RNPLib.rnp_output_t();
     RNPLib.rnp_output_to_memory(output.address(), 0);
 
     let op;
     if (args.encrypt) {
-      op = new RNPLib.rnp_op_encrypt_t;
-      if (RNPLib.rnp_op_encrypt_create(op.address(), RNPLib.ffi,
-          input, output)) {
+      op = new RNPLib.rnp_op_encrypt_t();
+      if (
+        RNPLib.rnp_op_encrypt_create(op.address(), RNPLib.ffi, input, output)
+      ) {
         throw new Error("rnp_op_encrypt_create failed");
       }
     } else if (args.sign) {
-      op = new RNPLib.rnp_op_sign_t;
+      op = new RNPLib.rnp_op_sign_t();
       if (args.sigTypeClear) {
-        if (RNPLib.rnp_op_sign_cleartext_create(op.address(), RNPLib.ffi,
-            input, output)) {
+        if (
+          RNPLib.rnp_op_sign_cleartext_create(
+            op.address(),
+            RNPLib.ffi,
+            input,
+            output
+          )
+        ) {
           throw new Error("rnp_op_sign_cleartext_create failed");
         }
-      } else  if (args.sigTypeDetached) {
-        if (RNPLib.rnp_op_sign_detached_create(op.address(), RNPLib.ffi,
-            input, output)) {
+      } else if (args.sigTypeDetached) {
+        if (
+          RNPLib.rnp_op_sign_detached_create(
+            op.address(),
+            RNPLib.ffi,
+            input,
+            output
+          )
+        ) {
           throw new Error("rnp_op_sign_detached_create failed");
         }
       } else {
-        throw new Error("not yet implemented scenario: signing, neither clear nor encrypt, without encryption");
+        throw new Error(
+          "not yet implemented scenario: signing, neither clear nor encrypt, without encryption"
+        );
       }
     } else {
       throw new Error("invalid parameters, neither encrypt nor sign");
     }
 
     let senderKey = null;
     if (args.sign || args.encryptToSender) {
       senderKey = this.getKeyHandleByIdentifier(args.sender);
@@ -816,50 +882,56 @@ var RNP = {
         let use_sub = null;
         if (!this.isKeyUsableFor(senderKey, str_sign)) {
           use_sub = this.getSuitableSubkey(senderKey, str_sign);
           if (!use_sub) {
             throw new Error("no suitable subkey found for " + str_sign);
           }
         }
         if (args.encrypt) {
-          if (RNPLib.rnp_op_encrypt_add_signature(op, 
-              (use_sub != null) ? use_sub : senderKey, 
-              null)) {
+          if (
+            RNPLib.rnp_op_encrypt_add_signature(
+              op,
+              use_sub != null ? use_sub : senderKey,
+              null
+            )
+          ) {
             throw new Error("rnp_op_encrypt_add_signature failed");
           }
-        } else {
-          if (RNPLib.rnp_op_sign_add_signature(op, 
-              use_sub ? use_sub : senderKey, 
-              null)) {
-            throw new Error("rnp_op_sign_add_signature failed");
-          }
+        } else if (
+          RNPLib.rnp_op_sign_add_signature(
+            op,
+            use_sub ? use_sub : senderKey,
+            null
+          )
+        ) {
+          throw new Error("rnp_op_sign_add_signature failed");
         }
         if (use_sub) {
           RNPLib.rnp_key_handle_destroy(use_sub);
         }
       }
       RNPLib.rnp_key_handle_destroy(senderKey);
     }
 
     if (args.encrypt) {
       for (let id in args.to) {
         let toKey = this.getKeyHandleByIdentifier(args.to[id]);
         if (!toKey) {
-          resultStatus.statusFlags |= EnigmailConstants.INVALID_RECIPIENT
+          resultStatus.statusFlags |= EnigmailConstants.INVALID_RECIPIENT;
           return null;
         }
         this.addSuitableEncryptKey(toKey, op);
         RNPLib.rnp_key_handle_destroy(toKey);
       }
 
       for (let id in args.bcc) {
         let bccKey = this.getKeyHandleByIdentifier(args.bcc[id]);
         if (!bccKey) {
-          resultStatus.statusFlags |= EnigmailConstants.INVALID_RECIPIENT
+          resultStatus.statusFlags |= EnigmailConstants.INVALID_RECIPIENT;
           return null;
         }
         this.addSuitableEncryptKey(bccKey, op);
         RNPLib.rnp_key_handle_destroy(bccKey);
       }
 
       // TODO decide if our compatibility requirements allow us to
       // use AEAD
@@ -877,174 +949,187 @@ var RNP = {
         throw new Error("rnp_op_encrypt_set_armor failed");
       }
 
       let rv = RNPLib.rnp_op_encrypt_execute(op);
       if (rv) {
         throw new Error("rnp_op_encrypt_execute failed: " + rv);
       }
       RNPLib.rnp_op_encrypt_destroy(op);
-
     } else {
       RNPLib.rnp_op_sign_set_hash(op, "SHA256");
       // TODO, map args.signatureHash string to RNP and call
       //       rnp_op_encrypt_set_hash
 
       RNPLib.rnp_op_sign_set_armor(op, args.armor);
 
       RNPLib.rnp_op_sign_execute(op);
       RNPLib.rnp_op_sign_destroy(op);
     }
-    
+
     RNPLib.rnp_input_destroy(input);
 
     let result = null;
 
     let result_buf = new ctypes.uint8_t.ptr();
     let result_len = new ctypes.size_t();
-    if (!RNPLib.rnp_output_memory_get_buf(output, result_buf.address(),
-                                          result_len.address(), false)) {
+    if (
+      !RNPLib.rnp_output_memory_get_buf(
+        output,
+        result_buf.address(),
+        result_len.address(),
+        false
+      )
+    ) {
       console.debug("encrypt result len: " + result_len.value);
       //let buf_array = ctypes.cast(result_buf, ctypes.uint8_t.array(result_len.value).ptr).contents;
       //let char_array = ctypes.cast(buf_array, ctypes.char.array(result_len.value));
 
       let char_array = ctypes.cast(
         result_buf,
         ctypes.char.array(result_len.value).ptr
       ).contents;
 
       result = char_array.readString();
       console.debug(result);
     }
 
     RNPLib.rnp_output_destroy(output);
 
     resultStatus.exitCode = 0;
-    
+
     if (args.encrypt) {
       resultStatus.statusFlags |= EnigmailConstants.END_ENCRYPTION;
     }
 
     if (args.sign) {
       resultStatus.statusFlags |= EnigmailConstants.SIG_CREATED;
     }
-    
+
     return result;
   },
 
   findKeyByEmail(id) {
     if (!id.startsWith("<") || !id.endsWith(">")) {
       throw new Error("invalid parameter given to findKeyByEmail");
     }
 
-    let keys = [];
     let rv;
 
-    let iter = new RNPLib.rnp_identifier_iterator_t;
+    let iter = new RNPLib.rnp_identifier_iterator_t();
     let grip = new ctypes.char.ptr();
 
-    rv = RNPLib.rnp_identifier_iterator_create(RNPLib.ffi, iter.address(), "grip");
+    rv = RNPLib.rnp_identifier_iterator_create(
+      RNPLib.ffi,
+      iter.address(),
+      "grip"
+    );
     if (rv) {
       return null;
     }
-    
+
     let foundHandle = null;
-    while (!foundHandle && !RNPLib.rnp_identifier_iterator_next(iter, grip.address())) {
+    while (
+      !foundHandle &&
+      !RNPLib.rnp_identifier_iterator_next(iter, grip.address())
+    ) {
       if (grip.isNull()) {
         break;
       }
 
       let have_handle = false;
-      let handle = new RNPLib.rnp_key_handle_t;
+      let handle = new RNPLib.rnp_key_handle_t();
 
       try {
-        let is_subkey = new ctypes.bool;
-        let uid_count = new ctypes.size_t;
+        let is_subkey = new ctypes.bool();
+        let uid_count = new ctypes.size_t();
 
         if (RNPLib.rnp_locate_key(RNPLib.ffi, "grip", grip, handle.address())) {
           throw new Error("rnp_locate_key failed");
         }
         have_handle = true;
         if (RNPLib.rnp_key_is_sub(handle, is_subkey.address())) {
           throw new Error("rnp_key_is_sub failed");
         }
         if (is_subkey.value) {
           continue;
         }
 
-        let key_revoked = new ctypes.bool;
+        let key_revoked = new ctypes.bool();
         if (RNPLib.rnp_key_is_revoked(handle, key_revoked.address())) {
           throw new Error("rnp_key_is_revoked failed");
         }
 
         if (key_revoked.value) {
           continue;
         }
 
         if (RNPLib.rnp_key_get_uid_count(handle, uid_count.address())) {
           throw new Error("rnp_key_get_uid_count failed");
         }
         console.debug("rnp_key_get_uid_count: " + uid_count.value);
         for (let i = 0; i < uid_count.value; i++) {
-          let uid_handle = new RNPLib.rnp_uid_handle_t;
-          let is_revoked = new ctypes.bool;
+          let uid_handle = new RNPLib.rnp_uid_handle_t();
+          let is_revoked = new ctypes.bool();
 
-          if (RNPLib.rnp_key_get_uid_handle_at(handle, i, uid_handle.address())) {
+          if (
+            RNPLib.rnp_key_get_uid_handle_at(handle, i, uid_handle.address())
+          ) {
             throw new Error("rnp_key_get_uid_handle_at failed");
           }
 
           if (RNPLib.rnp_uid_is_revoked(uid_handle, is_revoked.address())) {
             throw new Error("rnp_uid_is_revoked failed");
           }
 
           if (!is_revoked.value) {
-            let uid_str = new ctypes.char.ptr;
+            let uid_str = new ctypes.char.ptr();
             if (RNPLib.rnp_key_get_uid_at(handle, i, uid_str.address())) {
               throw new Error("rnp_key_get_uid_at failed");
             }
 
             let userId = uid_str.readString();
-            
+
             if (userId.includes(id)) {
               foundHandle = handle;
             }
-            
+
             RNPLib.rnp_buffer_destroy(uid_str);
           }
 
           RNPLib.rnp_uid_handle_destroy(uid_handle);
         }
-
       } catch (ex) {
         console.log(ex);
       } finally {
         if (!foundHandle && have_handle) {
           RNPLib.rnp_key_handle_destroy(handle);
         }
       }
     }
 
     RNPLib.rnp_identifier_iterator_destroy(iter);
-    
+
     return foundHandle;
   },
 
   getPublicKey(id) {
     let result = "";
     let key = this.getKeyHandleByIdentifier(id);
 
     if (key.isNull()) {
       return result;
     }
 
-    let flags = RNPLib.RNP_KEY_EXPORT_ARMORED | 
-                RNPLib.RNP_KEY_EXPORT_PUBLIC | 
-                RNPLib.RNP_KEY_EXPORT_SUBKEYS;
+    let flags =
+      RNPLib.RNP_KEY_EXPORT_ARMORED |
+      RNPLib.RNP_KEY_EXPORT_PUBLIC |
+      RNPLib.RNP_KEY_EXPORT_SUBKEYS;
 
-    let output_to_memory = new RNPLib.rnp_output_t;
+    let output_to_memory = new RNPLib.rnp_output_t();
     RNPLib.rnp_output_to_memory(output_to_memory.address(), 0);
 
     if (RNPLib.rnp_key_export(key, output_to_memory, flags)) {
       throw new Error("rnp_key_export failed");
     }
 
     let result_buf = new ctypes.uint8_t.ptr();
     let result_len = new ctypes.size_t();
--- a/mail/extensions/openpgp/content/modules/rnpLib.jsm
+++ b/mail/extensions/openpgp/content/modules/rnpLib.jsm
@@ -104,124 +104,142 @@ var RNPLib;
 
 function enableRNPLibJS() {
   // this must be delayed until after "librnp" is initialized
 
   RNPLib = {
     path: librnpPath,
 
     ffi: null,
-    
+
     getFilenames() {
       let names = {};
 
       let secFile = EnigmailApp.getProfileDirectory();
       secFile.append("secring.gpg");
       let pubFile = EnigmailApp.getProfileDirectory();
       pubFile.append("pubring.gpg");
-      
+
       names.secring = secFile.path;
       names.pubring = pubFile.path;
 
       return names;
     },
-    
+
     init() {
       console.log("===> RNPLib.init()\n");
 
-      this.ffi = new rnp_ffi_t;
+      this.ffi = new rnp_ffi_t();
       if (this.rnp_ffi_create(this.ffi.address(), "GPG", "GPG")) {
         throw new Error("Couldn't initialize librnp.");
       }
-      
+
       this.rnp_ffi_set_log_fd(this.ffi, 2); // stderr
 
       this.keep_password_cb_alive = rnp_password_cb_t(
         this.password_cb,
         this, // this value used while executing callback
         false // callback return value if exception is thrown
       );
       this.rnp_ffi_set_pass_provider(
         this.ffi,
         this.keep_password_cb_alive,
         null
       );
 
       let filenames = this.getFilenames();
 
-      let input_from_path = new rnp_input_t;
+      let input_from_path = new rnp_input_t();
       this.rnp_input_from_path(input_from_path.address(), filenames.pubring);
       this.rnp_load_keys(
         this.ffi,
         "GPG",
         input_from_path,
         this.RNP_LOAD_SAVE_PUBLIC_KEYS
       );
       this.rnp_input_destroy(input_from_path);
 
-      let in2 = new rnp_input_t;
+      let in2 = new rnp_input_t();
 
       this.rnp_input_from_path(in2.address(), filenames.secring);
       this.rnp_load_keys(this.ffi, "GPG", in2, this.RNP_LOAD_SAVE_SECRET_KEYS);
       this.rnp_input_destroy(in2);
 
       input_from_path = null;
       in2 = null;
 
-      let pubnum = new ctypes.size_t;
+      let pubnum = new ctypes.size_t();
       this.rnp_get_public_key_count(this.ffi, pubnum.address());
 
-      let secnum = new ctypes.size_t;
+      let secnum = new ctypes.size_t();
       this.rnp_get_secret_key_count(this.ffi, secnum.address());
 
       console.log("public keys: " + pubnum + ", secret keys: " + secnum);
       console.log(
         "public keys: " + pubnum.value + ", secret keys: " + secnum.value
       );
 
       /*
       if (this.rnp_ffi_destroy(this.ffi)) {
         throw new Error("Couldn't destroy librnp.");
       }
       */
       return true;
     },
-    
+
     saveKeys() {
       let filenames = this.getFilenames();
 
-      let rv;
-      let output_to_path = new rnp_output_t;
-      rv = this.rnp_output_to_path(output_to_path.address(), filenames.pubring);
-      rv = this.rnp_save_keys(
-        this.ffi,
-        "GPG",
-        output_to_path,
-        this.RNP_LOAD_SAVE_PUBLIC_KEYS
-      );
+      let output_to_path = new rnp_output_t();
+      if (
+        this.rnp_output_to_path(output_to_path.address(), filenames.pubring)
+      ) {
+        throw new Error("rnp_output_to_path failed");
+      }
+      if (
+        this.rnp_save_keys(
+          this.ffi,
+          "GPG",
+          output_to_path,
+          this.RNP_LOAD_SAVE_PUBLIC_KEYS
+        )
+      ) {
+        throw new Error("rnp_save_keys failed");
+      }
       this.rnp_output_destroy(output_to_path);
 
-      let out2 = new rnp_output_t;
+      let out2 = new rnp_output_t();
 
-      rv = this.rnp_output_to_path(out2.address(), filenames.secring);
-      rv = this.rnp_save_keys(this.ffi, "GPG", out2, this.RNP_LOAD_SAVE_SECRET_KEYS);
+      if (this.rnp_output_to_path(out2.address(), filenames.secring)) {
+        throw new Error("rnp_output_to_path failed");
+      }
+      if (
+        this.rnp_save_keys(
+          this.ffi,
+          "GPG",
+          out2,
+          this.RNP_LOAD_SAVE_SECRET_KEYS
+        )
+      ) {
+        throw new Error("rnp_save_keys failed");
+      }
       this.rnp_output_destroy(out2);
 
       output_to_path = null;
       out2 = null;
     },
 
     keep_password_cb_alive: null,
 
     password_cb(ffi, app_ctx, key, pgp_context, buf, buf_len) {
       console.log(
         "in RNPLib.password_cb, context: " + pgp_context.readString()
       );
       console.log("max_len: " + buf_len);
-      
+
       let pass = OpenPGPMasterpass.retrieveOpenPGPPassword();
       var passCTypes = ctypes.char.array()(pass); // UTF-8
       let passLen = passCTypes.length;
 
       if (buf_len < passLen) {
         return false;
       }
 
@@ -247,17 +265,17 @@ function enableRNPLibJS() {
     ),
 
     rnp_ffi_destroy: librnp.declare(
       "rnp_ffi_destroy",
       abi,
       rnp_result_t,
       rnp_ffi_t
     ),
-    
+
     rnp_ffi_set_log_fd: librnp.declare(
       "rnp_ffi_set_log_fd",
       abi,
       rnp_result_t,
       rnp_ffi_t,
       ctypes.int
     ),
 
@@ -367,67 +385,67 @@ function enableRNPLibJS() {
     rnp_ffi_set_pass_provider: librnp.declare(
       "rnp_ffi_set_pass_provider",
       abi,
       rnp_result_t,
       rnp_ffi_t,
       rnp_password_cb_t,
       ctypes.void_t.ptr
     ),
-    
+
     rnp_identifier_iterator_create: librnp.declare(
       "rnp_identifier_iterator_create",
       abi,
       rnp_result_t,
       rnp_ffi_t,
       rnp_identifier_iterator_t.ptr,
       ctypes.char.ptr
     ),
 
     rnp_identifier_iterator_next: librnp.declare(
       "rnp_identifier_iterator_next",
       abi,
       rnp_result_t,
       rnp_identifier_iterator_t,
       ctypes.char.ptr.ptr
     ),
-    
+
     rnp_identifier_iterator_destroy: librnp.declare(
       "rnp_identifier_iterator_destroy",
       abi,
       rnp_result_t,
       rnp_identifier_iterator_t
     ),
-    
+
     rnp_locate_key: librnp.declare(
       "rnp_locate_key",
       abi,
       rnp_result_t,
       rnp_ffi_t,
       ctypes.char.ptr,
       ctypes.char.ptr,
       rnp_key_handle_t.ptr
     ),
-    
+
     rnp_key_handle_destroy: librnp.declare(
       "rnp_key_handle_destroy",
       abi,
       rnp_result_t,
       rnp_key_handle_t
     ),
-    
+
     rnp_key_allows_usage: librnp.declare(
       "rnp_key_allows_usage",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.char.ptr,
       ctypes.bool.ptr
     ),
-    
+
     rnp_key_is_sub: librnp.declare(
       "rnp_key_is_sub",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.bool.ptr
     ),
 
@@ -449,33 +467,33 @@ function enableRNPLibJS() {
 
     rnp_key_have_public: librnp.declare(
       "rnp_key_have_public",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.bool.ptr
     ),
-    
+
     rnp_key_get_fprint: librnp.declare(
       "rnp_key_get_fprint",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.char.ptr.ptr
     ),
 
     rnp_key_get_keyid: librnp.declare(
       "rnp_key_get_keyid",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.char.ptr.ptr
     ),
-    
+
     rnp_key_get_alg: librnp.declare(
       "rnp_key_get_alg",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.char.ptr.ptr
     ),
 
@@ -489,49 +507,49 @@ function enableRNPLibJS() {
 
     rnp_key_get_primary_grip: librnp.declare(
       "rnp_key_get_primary_grip",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.char.ptr.ptr
     ),
-    
+
     rnp_key_is_revoked: librnp.declare(
       "rnp_key_is_revoked",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.bool.ptr
     ),
 
-   rnp_buffer_destroy: librnp.declare(
+    rnp_buffer_destroy: librnp.declare(
       "rnp_buffer_destroy",
       abi,
       ctypes.void_t,
       ctypes.void_t.ptr
     ),
-    
+
     rnp_key_get_subkey_count: librnp.declare(
       "rnp_key_get_subkey_count",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.size_t.ptr
     ),
-    
+
     rnp_key_get_subkey_at: librnp.declare(
       "rnp_key_get_subkey_at",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.size_t,
       rnp_key_handle_t.ptr
     ),
-    
+
     rnp_key_get_creation: librnp.declare(
       "rnp_key_get_creation",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.uint32_t.ptr
     ),
 
@@ -594,43 +612,43 @@ function enableRNPLibJS() {
 
     rnp_key_unlock: librnp.declare(
       "rnp_key_unlock",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.char.ptr
     ),
-    
+
     rnp_key_lock: librnp.declare(
       "rnp_key_lock",
       abi,
       rnp_result_t,
       rnp_key_handle_t
     ),
 
     rnp_op_generate_create: librnp.declare(
       "rnp_op_generate_create",
       abi,
       rnp_result_t,
       rnp_op_generate_t.ptr,
       rnp_ffi_t,
       ctypes.char.ptr
     ),
-    
+
     rnp_op_generate_subkey_create: librnp.declare(
       "rnp_op_generate_subkey_create",
       abi,
       rnp_result_t,
       rnp_op_generate_t.ptr,
       rnp_ffi_t,
       rnp_key_handle_t,
       ctypes.char.ptr
     ),
-    
+
     rnp_op_generate_set_bits: librnp.declare(
       "rnp_op_generate_set_bits",
       abi,
       rnp_result_t,
       rnp_op_generate_t,
       ctypes.uint32_t
     ),
 
@@ -665,52 +683,52 @@ function enableRNPLibJS() {
       rnp_op_generate_t,
       ctypes.uint32_t
     ),
 
     rnp_op_generate_execute: librnp.declare(
       "rnp_op_generate_execute",
       abi,
       rnp_result_t,
-      rnp_op_generate_t,
+      rnp_op_generate_t
     ),
 
     rnp_op_generate_get_key: librnp.declare(
       "rnp_op_generate_get_key",
       abi,
       rnp_result_t,
       rnp_op_generate_t,
       rnp_key_handle_t.ptr
     ),
 
     rnp_op_generate_destroy: librnp.declare(
       "rnp_op_generate_destroy",
       abi,
       rnp_result_t,
-      rnp_op_generate_t,
+      rnp_op_generate_t
     ),
-    
+
     rnp_import_keys: librnp.declare(
       "rnp_import_keys",
       abi,
       rnp_result_t,
       rnp_ffi_t,
       rnp_input_t,
       ctypes.uint32_t,
       ctypes.char.ptr.ptr
     ),
-    
+
     rnp_key_remove: librnp.declare(
       "rnp_key_remove",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       ctypes.uint32_t
     ),
-    
+
     rnp_op_encrypt_create: librnp.declare(
       "rnp_op_encrypt_create",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t.ptr,
       rnp_ffi_t,
       rnp_input_t,
       rnp_output_t
@@ -730,59 +748,59 @@ function enableRNPLibJS() {
       "rnp_op_sign_detached_create",
       abi,
       rnp_result_t,
       rnp_op_sign_t.ptr,
       rnp_ffi_t,
       rnp_input_t,
       rnp_output_t
     ),
-        
+
     rnp_op_encrypt_add_recipient: librnp.declare(
       "rnp_op_encrypt_add_recipient",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t,
       rnp_key_handle_t
     ),
-    
+
     rnp_op_encrypt_add_signature: librnp.declare(
       "rnp_op_encrypt_add_signature",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t,
       rnp_key_handle_t,
       rnp_op_sign_signature_t.ptr
     ),
-    
+
     rnp_op_sign_add_signature: librnp.declare(
       "rnp_op_sign_add_signature",
       abi,
       rnp_result_t,
       rnp_op_sign_t,
       rnp_key_handle_t,
       rnp_op_sign_signature_t.ptr
     ),
-    
+
     rnp_op_encrypt_set_armor: librnp.declare(
       "rnp_op_encrypt_set_armor",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t,
       ctypes.bool
     ),
 
     rnp_op_sign_set_armor: librnp.declare(
       "rnp_op_sign_set_armor",
       abi,
       rnp_result_t,
       rnp_op_sign_t,
       ctypes.bool
     ),
-    
+
     rnp_op_encrypt_set_hash: librnp.declare(
       "rnp_op_encrypt_set_hash",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t,
       ctypes.char.ptr
     ),
 
@@ -796,38 +814,38 @@ function enableRNPLibJS() {
 
     rnp_op_encrypt_set_cipher: librnp.declare(
       "rnp_op_encrypt_set_cipher",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t,
       ctypes.char.ptr
     ),
-    
+
     rnp_op_sign_execute: librnp.declare(
       "rnp_op_sign_execute",
       abi,
       rnp_result_t,
       rnp_op_sign_t
     ),
-    
+
     rnp_op_sign_destroy: librnp.declare(
       "rnp_op_sign_destroy",
       abi,
       rnp_result_t,
       rnp_op_sign_t
     ),
-    
+
     rnp_op_encrypt_execute: librnp.declare(
       "rnp_op_encrypt_execute",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t
     ),
-    
+
     rnp_op_encrypt_destroy: librnp.declare(
       "rnp_op_encrypt_destroy",
       abi,
       rnp_result_t,
       rnp_op_encrypt_t
     ),
 
     rnp_key_export: librnp.declare(
@@ -846,28 +864,27 @@ function enableRNPLibJS() {
     rnp_output_t,
     rnp_key_handle_t,
     rnp_uid_handle_t,
     rnp_identifier_iterator_t,
     rnp_op_generate_t,
     rnp_op_encrypt_t,
     rnp_op_sign_t,
     rnp_op_sign_signature_t,
-    
+
     RNP_LOAD_SAVE_PUBLIC_KEYS: 1,
-    
+
     RNP_LOAD_SAVE_SECRET_KEYS: 2,
-    
+
     RNP_KEY_REMOVE_PUBLIC: 1,
-    
+
     RNP_KEY_REMOVE_SECRET: 2,
-    
+
     RNP_KEY_EXPORT_ARMORED: 1,
     RNP_KEY_EXPORT_PUBLIC: 2,
     RNP_KEY_EXPORT_SECRET: 4,
     RNP_KEY_EXPORT_SUBKEYS: 8,
-
   };
 }
 
 // exports
 
 const EXPORTED_SYMBOLS = ["RNPLibLoader"];
--- a/mail/extensions/openpgp/content/modules/rules.jsm
+++ b/mail/extensions/openpgp/content/modules/rules.jsm
@@ -3,110 +3,126 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailRules"];
 
+/*EnigmailFuncs: false, : false, : false, : false, : false */
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailApp = ChromeUtils.import(
+  "chrome://openpgp/content/modules/app.jsm"
+).EnigmailApp;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
 
-/*EnigmailFuncs: false, : false, : false, : false, : false */
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
+const getKeyRing = EnigmailLazy.loader(
+  "enigmail/keyRing.jsm",
+  "EnigmailKeyRing"
+);
 
-const getKeyRing = EnigmailLazy.loader("enigmail/keyRing.jsm", "EnigmailKeyRing");
-
-const NS_RDONLY = 0x01;
-const NS_WRONLY = 0x02;
-const NS_CREATE_FILE = 0x08;
-const NS_TRUNCATE = 0x20;
 const DEFAULT_FILE_PERMS = 0o600;
 
 const rulesListHolder = {
-  rulesList: null
+  rulesList: null,
 };
 
 var EnigmailRules = {
-
-  getRulesFile: function() {
+  getRulesFile() {
     EnigmailLog.DEBUG("rules.jsm: getRulesFile()\n");
     var rulesFile = EnigmailApp.getProfileDirectory();
     rulesFile.append("pgprules.xml");
     return rulesFile;
   },
 
-  loadRulesFile: function() {
-    var flags = NS_RDONLY;
+  loadRulesFile() {
     var rulesFile = this.getRulesFile();
     if (rulesFile.exists()) {
       var fileContents = EnigmailFiles.readFile(rulesFile);
 
       return this.loadRulesFromString(fileContents);
     }
 
     return false;
   },
 
-  loadRulesFromString: function(contents) {
+  loadRulesFromString(contents) {
     EnigmailLog.DEBUG("rules.jsm: loadRulesFromString()\n");
     if (contents.length === 0 || contents.search(/^\s*$/) === 0) {
       return false;
     }
 
     var domParser;
     try {
       domParser = new DOMParser();
     } catch (ex) {
-      domParser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
+      domParser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(
+        Ci.nsIDOMParser
+      );
     }
     rulesListHolder.rulesList = domParser.parseFromString(contents, "text/xml");
 
     return true;
   },
 
-  saveRulesFile: function() {
+  saveRulesFile() {
     EnigmailLog.DEBUG("rules.jsm: saveRulesFile()\n");
 
-    var flags = NS_WRONLY | NS_CREATE_FILE | NS_TRUNCATE;
     var domSerializer;
 
     try {
       domSerializer = new XMLSerializer();
     } catch (ex) {
-      domSerializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Ci.nsIDOMSerializer);
+      domSerializer = Cc[
+        "@mozilla.org/xmlextras/xmlserializer;1"
+      ].createInstance(Ci.nsIDOMSerializer);
     }
 
     var rulesFile = this.getRulesFile();
     if (rulesFile) {
       if (rulesListHolder.rulesList) {
         // the rule list is not empty -> write into file
-        return EnigmailFiles.writeFileContents(rulesFile.path,
+        return EnigmailFiles.writeFileContents(
+          rulesFile.path,
           domSerializer.serializeToString(rulesListHolder.rulesList.firstChild),
-          DEFAULT_FILE_PERMS);
-      } else {
-        // empty rule list -> delete rules file
-        try {
-          rulesFile.remove(false);
-        } catch (ex) {}
-        return true;
+          DEFAULT_FILE_PERMS
+        );
       }
-    } else {
-      return false;
+      // empty rule list -> delete rules file
+      try {
+        rulesFile.remove(false);
+      } catch (ex) {}
+      return true;
     }
+    return false;
   },
 
-  getRulesData: function(rulesListObj) {
+  getRulesData(rulesListObj) {
     EnigmailLog.DEBUG("rules.jsm: getRulesData()\n");
 
     var ret = true;
 
     if (!rulesListHolder.rulesList) {
       ret = this.loadRulesFile();
     }
 
@@ -135,122 +151,152 @@ var EnigmailRules = {
    * @param pgpMime:     Number  - 0/1/2 as defined below
    * @param flags:       Number  - 0: no flags / 1: negate rule
    *
    * sign/encrypt/pgpMime values:
    *  0: Disable the action (= "Never")
    *  1: Use the setting in Message Composition
    *  2: Enable the action (= "Always")
    */
-  addRule: function(appendToEnd, toAddress, keyList, sign, encrypt, pgpMime, flags) {
+  addRule(appendToEnd, toAddress, keyList, sign, encrypt, pgpMime, flags) {
     EnigmailLog.DEBUG("rules.jsm: addRule()\n");
     var domParser;
     if (!rulesListHolder.rulesList) {
       try {
         domParser = new DOMParser();
       } catch (ex) {
-        domParser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
+        domParser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(
+          Ci.nsIDOMParser
+        );
       }
 
-      rulesListHolder.rulesList = domParser.parseFromString("<pgpRuleList/>", "text/xml");
+      rulesListHolder.rulesList = domParser.parseFromString(
+        "<pgpRuleList/>",
+        "text/xml"
+      );
     }
-    var negate = (flags & 1);
     var rule = rulesListHolder.rulesList.createElement("pgpRule");
     rule.setAttribute("email", toAddress.toLowerCase());
     rule.setAttribute("keyId", keyList);
     rule.setAttribute("sign", sign);
     rule.setAttribute("encrypt", encrypt);
     rule.setAttribute("pgpMime", pgpMime);
     rule.setAttribute("negateRule", flags);
     var origFirstChild = rulesListHolder.rulesList.firstChild.firstChild;
 
-    if (origFirstChild && (!appendToEnd)) {
+    if (origFirstChild && !appendToEnd) {
       rulesListHolder.rulesList.firstChild.insertBefore(rule, origFirstChild);
-      rulesListHolder.rulesList.firstChild.insertBefore(rulesListHolder.rulesList.createTextNode(EnigmailOS.isDosLike ? "\r\n" : "\n"), origFirstChild);
+      rulesListHolder.rulesList.firstChild.insertBefore(
+        rulesListHolder.rulesList.createTextNode(
+          EnigmailOS.isDosLike ? "\r\n" : "\n"
+        ),
+        origFirstChild
+      );
     } else {
       rulesListHolder.rulesList.firstChild.appendChild(rule);
-      rulesListHolder.rulesList.firstChild.appendChild(rulesListHolder.rulesList.createTextNode(EnigmailOS.isDosLike ? "\r\n" : "\n"));
+      rulesListHolder.rulesList.firstChild.appendChild(
+        rulesListHolder.rulesList.createTextNode(
+          EnigmailOS.isDosLike ? "\r\n" : "\n"
+        )
+      );
     }
   },
 
   /**
    * Create new rule or update existing rule if the rule already exists.
    * The key to decide if the rule exists is the email address (must match 1:1)
    *
    * @param ruleObj: Object with attributes {keyList, sign, encrypt, pgpMime, flags}
    * @return: Number: 0 - no update / 1 - rule updated / 2 - new rule created
    */
-  insertOrUpdateRule: function(ruleObj) {
-    if ((!("email" in ruleObj)) || ruleObj.email.length === 0) return 0;
+  insertOrUpdateRule(ruleObj) {
+    if (!("email" in ruleObj) || ruleObj.email.length === 0) {
+      return 0;
+    }
 
     let node = this.getRuleByEmail(ruleObj.email);
 
     if (node) {
       node.setAttribute("keyId", ruleObj.keyList);
       node.setAttribute("sign", ruleObj.sign);
       node.setAttribute("encrypt", ruleObj.encrypt);
       node.setAttribute("pgpMime", ruleObj.pgpMime);
       node.setAttribute("negateRule", ruleObj.flags);
       this.saveRulesFile();
 
       return 1;
     }
 
     // no rule matched, let's add the rule at the start of the list
-    this.addRule(false, ruleObj.email, ruleObj.keyList, ruleObj.sign, ruleObj.encrypt, ruleObj.pgpMime, ruleObj.flags);
+    this.addRule(
+      false,
+      ruleObj.email,
+      ruleObj.keyList,
+      ruleObj.sign,
+      ruleObj.encrypt,
+      ruleObj.pgpMime,
+      ruleObj.flags
+    );
     this.saveRulesFile();
 
     return 2;
   },
 
-
   /**
    * Get a rule if it matches exactly one email address
    *
    * @param emailAddr: String - emailAddress to search
    *
    * @return Object: node object (DOM object)
    */
-  getRuleByEmail: function(emailAddr) {
+  getRuleByEmail(emailAddr) {
     emailAddr = emailAddr.toLowerCase();
 
     if (emailAddr.search(/^\{.*\}$/) < 0) {
       emailAddr = "{" + emailAddr + "}";
     }
 
     let rulesListObj = {};
     this.getRulesData(rulesListObj);
     let rulesList = rulesListObj.value;
 
     if (rulesList) {
-      for (let node = rulesList.firstChild.firstChild; node; node = node.nextSibling) {
+      for (
+        let node = rulesList.firstChild.firstChild;
+        node;
+        node = node.nextSibling
+      ) {
         if (node.tagName == "pgpRule") {
           try {
             let nodeEmail = node.getAttribute("email");
             if (!nodeEmail) {
               continue;
             }
             if (nodeEmail.toLowerCase() === emailAddr) {
               return node;
             }
           } catch (ex) {
-            EnigmailLog.DEBUG("rules.jsm: getRuleByEmail(): ignore exception: " + ex.description + "\n");
+            EnigmailLog.DEBUG(
+              "rules.jsm: getRuleByEmail(): ignore exception: " +
+                ex.description +
+                "\n"
+            );
           }
         }
       }
     }
 
     return null;
   },
 
-  clearRules: function() {
+  clearRules() {
     rulesListHolder.rulesList = null;
   },
 
-  DEBUG_EmailList: function(name, list) {
+  DEBUG_EmailList(name, list) {
     EnigmailLog.DEBUG("           " + name + ":\n");
     for (let i = 0; i < list.length; i++) {
       let elem = list[i];
       let str = "            [" + i + "]: ";
       if (elem.orig) {
         str += "orig: '" + elem.orig + "'  ";
       }
       if (elem.addr) {
@@ -274,19 +320,30 @@ var EnigmailRules = {
    *  @matchedKeysObj.addrKeysList: all email/keys mappings (array of objects with addr as string and keys as comma separated string)
    *                                (does NOT contain emails for which no key was found)
    *  @matchedKeysObj.addrNoKeyList: list of emails that don't have a key according to rules
    *  @flagsObj:       return value for combined sign/encrype/pgpMime mode
    *                   values might be: 0='never', 1='maybe', 2='always', 3='conflict'
    *
    * @return:  false if error occurred or processing was canceled
    */
-  mapAddrsToKeys: function(emailAddrsStr, startDialogForMissingKeys, window,
-    matchedKeysObj, flagsObj) {
-    EnigmailLog.DEBUG("rules.jsm: mapAddrsToKeys(): emailAddrsStr=\"" + emailAddrsStr + "\" startDialogForMissingKeys=" + startDialogForMissingKeys + "\n");
+  mapAddrsToKeys(
+    emailAddrsStr,
+    startDialogForMissingKeys,
+    window,
+    matchedKeysObj,
+    flagsObj
+  ) {
+    EnigmailLog.DEBUG(
+      'rules.jsm: mapAddrsToKeys(): emailAddrsStr="' +
+        emailAddrsStr +
+        '" startDialogForMissingKeys=' +
+        startDialogForMissingKeys +
+        "\n"
+    );
 
     let enigmailSvc = EnigmailCore.getService();
     if (!enigmailSvc) {
       EnigmailLog.DEBUG("EnigmailCore Service is down\n");
       return false;
     }
 
     // initialize return value and the helper variables for them:
@@ -311,95 +368,126 @@ var EnigmailRules = {
       let orig = emailAddrList[i];
       if (orig) {
         let addr = null;
         try {
           addr = EnigmailFuncs.stripEmail(orig.toLowerCase());
         } catch (ex) {}
         if (addr) {
           let elem = {
-            orig: orig,
-            addr: addr
+            orig,
+            addr,
           };
           openList.push(elem);
         }
       }
     }
     //this.DEBUG_EmailList("openList", openList);
     let addrKeysList = []; // NEW: list of found email addresses and their associated keys
     let addrNoKeyList = []; // NEW: final list of email addresses that have no key according to rules
 
     // process recipient rules
     let rulesListObj = {};
     if (this.getRulesData(rulesListObj)) {
-
       let rulesList = rulesListObj.value;
       if (rulesList.firstChild.nodeName == "parsererror") {
-        EnigmailDialog.alert(window, "Invalid pgprules.xml file:\n" + rulesList.firstChild.textContent);
+        EnigmailDialog.alert(
+          window,
+          "Invalid pgprules.xml file:\n" + rulesList.firstChild.textContent
+        );
         return false;
       }
-      EnigmailLog.DEBUG("rules.jsm: mapAddrsToKeys(): rules successfully loaded; now process them\n");
+      EnigmailLog.DEBUG(
+        "rules.jsm: mapAddrsToKeys(): rules successfully loaded; now process them\n"
+      );
 
       // go through all rules to find match with email addresses
       // - note: only if the key field has a value, an address is done with processing
-      for (let node = rulesList.firstChild.firstChild; node; node = node.nextSibling) {
+      for (
+        let node = rulesList.firstChild.firstChild;
+        node;
+        node = node.nextSibling
+      ) {
         if (node.tagName == "pgpRule") {
           try {
             let rule = {};
             rule.email = node.getAttribute("email");
             if (!rule.email) {
               continue;
             }
             rule.negate = false;
             if (node.getAttribute("negateRule")) {
               rule.negate = Number(node.getAttribute("negateRule"));
             }
             if (!rule.negate) {
               rule.keyId = node.getAttribute("keyId");
               rule.sign = node.getAttribute("sign");
               rule.encrypt = node.getAttribute("encrypt");
               rule.pgpMime = node.getAttribute("pgpMime");
-              this.mapRuleToKeys(rule,
-                openList, flags, addrKeysList, addrNoKeyList, false);
+              this.mapRuleToKeys(
+                rule,
+                openList,
+                flags,
+                addrKeysList,
+                addrNoKeyList,
+                false
+              );
             }
             // no negate rule handling (turned off in dialog)
           } catch (ex) {
-            EnigmailLog.DEBUG("rules.jsm: mapAddrsToKeys(): ignore exception: " + ex.description + "\n");
+            EnigmailLog.DEBUG(
+              "rules.jsm: mapAddrsToKeys(): ignore exception: " +
+                ex.description +
+                "\n"
+            );
           }
         }
       }
 
       // go again through the list to find autocrypt:// prefixed rules
-      for (let node = rulesList.firstChild.firstChild; node; node = node.nextSibling) {
+      for (
+        let node = rulesList.firstChild.firstChild;
+        node;
+        node = node.nextSibling
+      ) {
         if (node.tagName == "pgpRule") {
           try {
             let rule = {};
             rule.email = node.getAttribute("email");
             if (!rule.email) {
               continue;
             }
             rule.negate = false;
             if (node.getAttribute("negateRule")) {
               rule.negate = Number(node.getAttribute("negateRule"));
             }
             if (!rule.negate) {
               rule.keyId = node.getAttribute("keyId");
               rule.sign = node.getAttribute("sign");
               rule.encrypt = node.getAttribute("encrypt");
               rule.pgpMime = node.getAttribute("pgpMime");
-              this.mapRuleToKeys(rule,
-                openList, flags, addrKeysList, addrNoKeyList, true);
+              this.mapRuleToKeys(
+                rule,
+                openList,
+                flags,
+                addrKeysList,
+                addrNoKeyList,
+                true
+              );
             }
             // no negate rule handling (turned off in dialog)
           } catch (ex) {
-            EnigmailLog.DEBUG("rules.jsm: mapAddrsToKeys(): ignore exception: " + ex.description + "\n");
+            EnigmailLog.DEBUG(
+              "rules.jsm: mapAddrsToKeys(): ignore exception: " +
+                ex.description +
+                "\n"
+            );
           }
         }
       }
-
     }
 
     // NOTE: here we have
     // - openList: the addresses not having any key assigned yet
     //             (and not marked as don't process any other rule)
     // - addresses with "don't process other rules" are in addrNoKeyList
     //this.DEBUG_EmailList("openList", openList);
     //this.DEBUG_EmailList("addrKeysList", addrKeysList);
@@ -408,29 +496,40 @@ var EnigmailRules = {
     // if requested: start dialog to add new rule for each missing key
     if (startDialogForMissingKeys) {
       let inputObj = {};
       let resultObj = {};
       for (let i = 0; i < openList.length; i++) {
         let theAddr = openList[i].addr;
         // start dialog only if the email address contains a @ or no 0x at the beginning:
         // - reason: newsgroups have neither @ nor 0x
-        if (theAddr.indexOf("@") != -1 || theAddr.indexOf("0x") !== 0) {
+        if (theAddr.includes("@") || theAddr.indexOf("0x") !== 0) {
           inputObj.toAddress = "{" + theAddr + "}";
           inputObj.options = "";
           inputObj.command = "add";
-          window.openDialog("chrome://openpgp/content/ui/enigmailSingleRcptSettings.xhtml", "",
-            "dialog,modal,centerscreen,resizable", inputObj, resultObj);
+          window.openDialog(
+            "chrome://openpgp/content/ui/enigmailSingleRcptSettings.xhtml",
+            "",
+            "dialog,modal,centerscreen,resizable",
+            inputObj,
+            resultObj
+          );
           if (resultObj.cancelled === true) {
             return false;
           }
 
           if (!resultObj.negate) {
-            this.mapRuleToKeys(resultObj,
-              openList, flags, addrKeysList, addrNoKeyList, false);
+            this.mapRuleToKeys(
+              resultObj,
+              openList,
+              flags,
+              addrKeysList,
+              addrNoKeyList,
+              false
+            );
           }
           // no negate rule handling (turned off in dialog)
         }
       }
     }
 
     // return value of OLD interface:
     // IFF we found keys, return keys AND unprocessed addresses in matchedKeysObj.value as comma-separated string
@@ -461,78 +560,109 @@ var EnigmailRules = {
     // return result from combining flags
     flagsObj.sign = flags.sign;
     flagsObj.encrypt = flags.encrypt;
     flagsObj.pgpMime = flags.pgpMime;
     flagsObj.value = true;
 
     EnigmailLog.DEBUG("   found keys:\n");
     for (let i = 0; i < matchedKeysObj.addrKeysList.length; i++) {
-      EnigmailLog.DEBUG("     " + matchedKeysObj.addrKeysList[i].addr + ": " + matchedKeysObj.addrKeysList[i].keys + "\n");
+      EnigmailLog.DEBUG(
+        "     " +
+          matchedKeysObj.addrKeysList[i].addr +
+          ": " +
+          matchedKeysObj.addrKeysList[i].keys +
+          "\n"
+      );
     }
     EnigmailLog.DEBUG("   addresses without keys:\n");
     for (let i = 0; i < matchedKeysObj.addrNoKeyList.length; i++) {
       EnigmailLog.DEBUG("     " + matchedKeysObj.addrNoKeyList[i].addr + "\n");
     }
     EnigmailLog.DEBUG("   old returned value:\n");
     EnigmailLog.DEBUG("     " + matchedKeysObj.value + "\n");
 
     return true;
   },
 
-  mapRuleToKeys: function(rule, openList, flags, addrKeysList, addrNoKeyList, isAutocryptEmail = false) {
+  mapRuleToKeys(
+    rule,
+    openList,
+    flags,
+    addrKeysList,
+    addrNoKeyList,
+    isAutocryptEmail = false
+  ) {
     //EnigmailLog.DEBUG("rules.jsm: mapRuleToKeys() rule.email='" + rule.email + "'\n");
     let ruleList = rule.email.toLowerCase().split(/[ ,;]+/);
     for (let ruleIndex = 0; ruleIndex < ruleList.length; ++ruleIndex) {
       let ruleEmailElem = ruleList[ruleIndex]; // ruleEmailElem has format such as '{name@qqq.de}' or '@qqq' or '{name' or '@qqq.de}'
       //EnigmailLog.DEBUG("   process ruleElem: '" + ruleEmailElem + "'\n");
       for (let openIndex = 0; openIndex < openList.length; ++openIndex) {
         let addr = openList[openIndex].addr;
         // search with { and } around because these are used as start and end markers in the rules:
         let idx;
 
         if (isAutocryptEmail) {
-          idx = ('{' + EnigmailConstants.AC_RULE_PREFIX + addr + '}').indexOf(ruleEmailElem);
+          idx = ("{" + EnigmailConstants.AC_RULE_PREFIX + addr + "}").indexOf(
+            ruleEmailElem
+          );
         } else {
-          idx = ('{' + addr + '}').indexOf(ruleEmailElem);
+          idx = ("{" + addr + "}").indexOf(ruleEmailElem);
         }
         if (idx >= 0) {
           if (ruleEmailElem == rule.email) {
-            EnigmailLog.DEBUG("rules.jsm: mapRuleToKeys(): for '" + addr + "' ('" + openList[openIndex].orig +
-              "') found matching rule element '" + ruleEmailElem + "'\n");
+            EnigmailLog.DEBUG(
+              "rules.jsm: mapRuleToKeys(): for '" +
+                addr +
+                "' ('" +
+                openList[openIndex].orig +
+                "') found matching rule element '" +
+                ruleEmailElem +
+                "'\n"
+            );
           } else {
-            EnigmailLog.DEBUG("rules.jsm: mapRuleToKeys(): for '" + addr + "' ('" + openList[openIndex].orig +
-              "') found matching rule element '" + ruleEmailElem + "' from '" + rule.email + "'\n");
+            EnigmailLog.DEBUG(
+              "rules.jsm: mapRuleToKeys(): for '" +
+                addr +
+                "' ('" +
+                openList[openIndex].orig +
+                "') found matching rule element '" +
+                ruleEmailElem +
+                "' from '" +
+                rule.email +
+                "'\n"
+            );
           }
 
-
-
           // process rule:
           // NOTE: rule.keyId might be:
           // - keys:  => assign keys to all matching emails
           //             and mark matching address as no longer open
           // - ".":   signals "Do not check further rules for the matching address"
           //          => mark all matching address as no longer open, but assign no keys
           //             (thus, add it to the addrNoKeyList)
           // - empty: Either if "Continue with next rule for the matching address"
           //          OR: if "Use the following OpenPGP keys:" with no keys and
           //              warning (will turn off encryption) acknowledged
           //          => then we only process the flags
 
           if (rule.keyId) {
             if (isAutocryptEmail) {
               let keyObj = getKeyRing().getKeyById(rule.keyId);
               if (keyObj) {
-                if (!(keyObj.getEncryptionValidity().keyValid)) {
+                if (!keyObj.getEncryptionValidity().keyValid) {
                   keyObj = null;
                   deleteAutocryptRule(addr);
                 }
               }
 
-              if (!keyObj) continue;
+              if (!keyObj) {
+                continue;
+              }
             }
 
             // move found address from openAdresses to corresponding list (with keys added)
             let elem = openList.splice(openIndex, 1)[0];
             --openIndex; // IMPORTANT because we remove element in the array we iterate on
             if (rule.keyId != ".") {
               // keys exist: assign keys as comma-separated string
               let ids = rule.keyId.replace(/[ ,;]+/g, ", ");
@@ -541,65 +671,82 @@ var EnigmailRules = {
             } else {
               // '.': no further rule processing and no key: addr was (finally) processed but without any key
               addrNoKeyList.push(elem);
             }
           }
 
           // process sign/encrypt/ppgMime settings
           flags.sign = this.combineFlagValues(flags.sign, Number(rule.sign));
-          flags.encrypt = this.combineFlagValues(flags.encrypt, Number(rule.encrypt));
-          flags.pgpMime = this.combineFlagValues(flags.pgpMime, Number(rule.pgpMime));
-
+          flags.encrypt = this.combineFlagValues(
+            flags.encrypt,
+            Number(rule.encrypt)
+          );
+          flags.pgpMime = this.combineFlagValues(
+            flags.pgpMime,
+            Number(rule.pgpMime)
+          );
         }
       }
     }
   },
 
   /**
    *  check for the attribute of type "sign"/"encrypt"/"pgpMime" of the passed node
    *  and combine its value with oldVal and check for conflicts
    *    values might be: 0='never', 1='maybe', 2='always', 3='conflict'
    *  @oldVal:      original input value
    *  @newVal:      new value to combine with
    *  @return: result value after applying the rule (0/1/2)
    *           and combining it with oldVal
    */
-  combineFlagValues: function(oldVal, newVal) {
+  combineFlagValues(oldVal, newVal) {
     //EnigmailLog.DEBUG("rules.jsm:    combineFlagValues(): oldVal=" + oldVal + " newVal=" + newVal + "\n");
 
     // conflict remains conflict
     if (oldVal === EnigmailConstants.ENIG_CONFLICT) {
       return EnigmailConstants.ENIG_CONFLICT;
     }
 
     // 'never' and 'always' triggers conflict:
-    if ((oldVal === EnigmailConstants.ENIG_NEVER && newVal === EnigmailConstants.ENIG_ALWAYS) || (oldVal === EnigmailConstants.ENIG_ALWAYS && newVal === EnigmailConstants.ENIG_NEVER)) {
+    if (
+      (oldVal === EnigmailConstants.ENIG_NEVER &&
+        newVal === EnigmailConstants.ENIG_ALWAYS) ||
+      (oldVal === EnigmailConstants.ENIG_ALWAYS &&
+        newVal === EnigmailConstants.ENIG_NEVER)
+    ) {
       return EnigmailConstants.ENIG_CONFLICT;
     }
 
     // if there is any 'never' return 'never'
     // - thus: 'never' and 'maybe' => 'never'
-    if (oldVal === EnigmailConstants.ENIG_NEVER || newVal === EnigmailConstants.ENIG_NEVER) {
+    if (
+      oldVal === EnigmailConstants.ENIG_NEVER ||
+      newVal === EnigmailConstants.ENIG_NEVER
+    ) {
       return EnigmailConstants.ENIG_NEVER;
     }
 
     // if there is any 'always' return 'always'
     // - thus: 'always' and 'maybe' => 'always'
-    if (oldVal === EnigmailConstants.ENIG_ALWAYS || newVal === EnigmailConstants.ENIG_ALWAYS) {
+    if (
+      oldVal === EnigmailConstants.ENIG_ALWAYS ||
+      newVal === EnigmailConstants.ENIG_ALWAYS
+    ) {
       return EnigmailConstants.ENIG_ALWAYS;
     }
 
     // here, both values are 'maybe', which we return then
     return EnigmailConstants.ENIG_UNDEF; // maybe
-  }
+  },
 };
 
-
 async function deleteAutocryptRule(emailAddr) {
-  const EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
+  const EnigmailAutocrypt = ChromeUtils.import(
+    "chrome://openpgp/content/modules/autocrypt.jsm"
+  ).EnigmailAutocrypt;
 
   await EnigmailAutocrypt.deleteUser(emailAddr, "1");
   // make sure that gossip rule is marked as "imported"
   await EnigmailAutocrypt.setKeyImported(null, emailAddr);
   // try to apply gossip key
   await EnigmailAutocrypt.importAutocryptKeys(emailAddr, true);
-}
\ No newline at end of file
+}
--- a/mail/extensions/openpgp/content/modules/searchCallback.jsm
+++ b/mail/extensions/openpgp/content/modules/searchCallback.jsm
@@ -3,68 +3,69 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailSearchCallback"];
 
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-
+const EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
 
 var EnigmailSearchCallback = {
   /**
-   * Set up a callback function on a textbox that tiggers an action. 
+   * Set up a callback function on a textbox that tiggers an action.
    * If ESC is pressed, the input field is emtpied; return triggers the action immediately.
    *
    * @param targetObj {XULElement}: the XUL element to observe
    * @param timoeoutObj {object}: timeoutObj.value will hold the timeout ID
    * @param actionCallback {function}: callback function that is called if something is typed
    * @param timeoutMs {number}: delay triggering the function (in miliseconds)
    */
-  setup: function(targetObj, timeoutObj, actionCallback, timeoutMs = 200) {
-
-
+  setup(targetObj, timeoutObj, actionCallback, timeoutMs = 200) {
     function applyActionImmediately() {
       if (timeoutObj.value) {
         EnigmailTimer.clearTimeout(timeoutObj.value);
         timeoutObj.value = null;
       }
       applyAction();
     }
 
     function applyAction() {
       actionCallback();
     }
 
     timeoutObj.value = null;
 
-
-    targetObj.addEventListener('keypress', function onKeyPress(event) {
-      if (event.type === "keypress") {
-        if (event.keyCode === 27) {
-          // Escape key
-          if (event.target.value !== "") {
-            event.target.value = "";
-            event.preventDefault();
-          }
-          applyActionImmediately();
+    targetObj.addEventListener(
+      "keypress",
+      function(event) {
+        if (event.type === "keypress") {
+          if (event.keyCode === 27) {
+            // Escape key
+            if (event.target.value !== "") {
+              event.target.value = "";
+              event.preventDefault();
+            }
+            applyActionImmediately();
 
-          return;
-        } else if (event.keyCode === 10 || event.keyCode === 13) {
-          // return key
-          applyActionImmediately();
-          event.preventDefault();
-          return;
+            return;
+          } else if (event.keyCode === 10 || event.keyCode === 13) {
+            // return key
+            applyActionImmediately();
+            event.preventDefault();
+            return;
+          }
         }
-      }
 
-      if (!timeoutObj.value) {
-        timeoutObj.value = EnigmailTimer.setTimeout(function() {
+        if (!timeoutObj.value) {
+          timeoutObj.value = EnigmailTimer.setTimeout(function() {
             timeoutObj.value = null;
             applyAction();
-          },
-          timeoutMs);
-      }
-    }, true);
-  }
-};
\ No newline at end of file
+          }, timeoutMs);
+        }
+      },
+      true
+    );
+  },
+};
--- a/mail/extensions/openpgp/content/modules/send.jsm
+++ b/mail/extensions/openpgp/content/modules/send.jsm
@@ -1,88 +1,106 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailSend"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
-const EnigmailRNG = ChromeUtils.import("chrome://openpgp/content/modules/rng.jsm").EnigmailRNG;
-var MailServices;
-try {
-  MailServices = ChromeUtils.import("resource:///modules/MailServices.jsm").MailServices;
-}
-catch (x){
-  MailServices = ChromeUtils.import("resource:///modules/mailServices.js").MailServices;
-}
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+const EnigmailRNG = ChromeUtils.import(
+  "chrome://openpgp/content/modules/rng.jsm"
+).EnigmailRNG;
 
 var EnigmailSend = {
   /**
    * Send out an email
    *
    * @param msgData    - String: complete MIME string of email (including all headers etc.)
    * @param compFields - Object: compose fields (nsIMsgCompFields)
    * @param listener   - Object: progress listener (nsIMsgSendListener)
    *
    * @return Boolean - true: everything was OK to send the message
    */
 
-  sendMessage: function(msgData, compFields, listener = null) {
+  sendMessage(msgData, compFields, listener = null) {
     EnigmailLog.DEBUG("EnigmailSend.sendMessage()\n");
     let tmpFile, msgIdentity;
     try {
       tmpFile = EnigmailFiles.getTempDirObj();
       tmpFile.append("message.eml");
       tmpFile.createUnique(0, 0o600);
-    }
-    catch (ex) {
+    } catch (ex) {
       return false;
     }
 
     EnigmailFiles.writeFileContents(tmpFile, msgData);
-    EnigmailLog.DEBUG("EnigmailSend.sendMessage: wrote file: " + tmpFile.path + "\n");
+    EnigmailLog.DEBUG(
+      "EnigmailSend.sendMessage: wrote file: " + tmpFile.path + "\n"
+    );
 
     try {
       msgIdentity = EnigmailStdlib.getIdentityForEmail(compFields.from);
-    }
-    catch (ex) {
+    } catch (ex) {
       msgIdentity = EnigmailStdlib.getDefaultIdentity();
     }
 
     if (!msgIdentity) {
       return false;
     }
 
-    EnigmailLog.DEBUG("EnigmailSend.sendMessage: identity key: " + msgIdentity.identity.key + "\n");
+    EnigmailLog.DEBUG(
+      "EnigmailSend.sendMessage: identity key: " +
+        msgIdentity.identity.key +
+        "\n"
+    );
 
     let acct = EnigmailFuncs.getAccountForIdentity(msgIdentity.identity);
-    if (!acct) return false;
+    if (!acct) {
+      return false;
+    }
 
-    EnigmailLog.DEBUG("EnigmailSend.sendMessage: account key: " + acct.key + "\n");
+    EnigmailLog.DEBUG(
+      "EnigmailSend.sendMessage: account key: " + acct.key + "\n"
+    );
 
-    let msgSend = Cc["@mozilla.org/messengercompose/send;1"].createInstance(Ci.nsIMsgSend);
-    msgSend.sendMessageFile(msgIdentity.identity,
+    let msgSend = Cc["@mozilla.org/messengercompose/send;1"].createInstance(
+      Ci.nsIMsgSend
+    );
+    msgSend.sendMessageFile(
+      msgIdentity.identity,
       acct.key,
       compFields,
       tmpFile,
       true, // Delete  File On Completion
-      false, (Services.io.offline ? Ci.nsIMsgSend.nsMsgQueueForLater : Ci.nsIMsgSend.nsMsgDeliverNow),
+      false,
+      Services.io.offline
+        ? Ci.nsIMsgSend.nsMsgQueueForLater
+        : Ci.nsIMsgSend.nsMsgDeliverNow,
       null,
       listener,
       null,
-      ""); // password
+      ""
+    ); // password
 
     return true;
   },
 
   /**
    * Send message (simplified API)
    *
    * @param aParams: Object -
@@ -98,49 +116,65 @@ var EnigmailSend = {
    *    - composeSecure (optional) (contains securityInfo for TB < 64)
    *
    * @param body: complete message source
    * @param callbackFunc: function(Boolean) - return true if message was sent successfully
    *                                           false otherwise
    *
    * @return Boolean - true: everything was OK to send the message
    */
-  simpleSendMessage: function(aParams, body, callbackFunc) {
+  simpleSendMessage(aParams, body, callbackFunc) {
     EnigmailLog.DEBUG("EnigmailSend.simpleSendMessage()\n");
-    let fields = Cc["@mozilla.org/messengercompose/composefields;1"]
-      .createInstance(Ci.nsIMsgCompFields);
+    let fields = Cc[
+      "@mozilla.org/messengercompose/composefields;1"
+    ].createInstance(Ci.nsIMsgCompFields);
     let identity = aParams.identity;
 
     fields.from = identity.email;
     fields.to = aParams.to;
-    if ("cc" in aParams) fields.cc = aParams.cc;
-    if ("bcc" in aParams) fields.bcc = aParams.bcc;
-    fields.returnReceipt = ("returnReceipt" in aParams) ? aParams.returnReceipt : identity.requestReturnReceipt;
-    fields.receiptHeaderType = ("receiptType" in aParams) ? aParams.receiptType : identity.receiptHeaderType;
-    fields.DSN = ("requestDsn" in aParams) ? aParams.requestDsn : identity.requestDSN;
+    if ("cc" in aParams) {
+      fields.cc = aParams.cc;
+    }
+    if ("bcc" in aParams) {
+      fields.bcc = aParams.bcc;
+    }
+    fields.returnReceipt =
+      "returnReceipt" in aParams
+        ? aParams.returnReceipt
+        : identity.requestReturnReceipt;
+    fields.receiptHeaderType =
+      "receiptType" in aParams
+        ? aParams.receiptType
+        : identity.receiptHeaderType;
+    fields.DSN =
+      "requestDsn" in aParams ? aParams.requestDsn : identity.requestDSN;
     if ("composeSecure" in aParams) {
       if ("securityInfo" in fields) {
         // TB < 64
         fields.securityInfo = aParams.securityInfo;
+      } else {
+        fields.composeSecure = aParams.composeSecure;
       }
-      else
-        fields.composeSecure = aParams.composeSecure;
     }
 
     fields.messageId = EnigmailRNG.generateRandomString(27) + "-enigmail";
     body = "Message-Id: " + fields.messageId + "\r\n" + body;
 
     let listener = {
-      onStartSending: function() {},
-      onProgress: function() {},
-      onStatus: function() {},
-      onGetDraftFolderURI: function() {},
-      onStopSending: function(aMsgID, aStatus, aMsg, aReturnFile) {
-        if (callbackFunc) callbackFunc(true);
+      onStartSending() {},
+      onProgress() {},
+      onStatus() {},
+      onGetDraftFolderURI() {},
+      onStopSending(aMsgID, aStatus, aMsg, aReturnFile) {
+        if (callbackFunc) {
+          callbackFunc(true);
+        }
       },
-      onSendNotPerformed: function(aMsgID, aStatus) {
-        if (callbackFunc) callbackFunc(false);
-      }
+      onSendNotPerformed(aMsgID, aStatus) {
+        if (callbackFunc) {
+          callbackFunc(false);
+        }
+      },
     };
 
     return this.sendMessage(body, fields, listener);
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/singletons.jsm
+++ b/mail/extensions/openpgp/content/modules/singletons.jsm
@@ -1,25 +1,24 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailSingletons"];
 
-
 var EnigmailSingletons = {
   // handle to most recent message reader window
   messageReader: null,
 
   // information about the last PGP/MIME decrypted message (mimeDecrypt)
   lastDecryptedMessage: {},
 
-  clearLastDecryptedMessage: function() {
+  clearLastDecryptedMessage() {
     let lm = this.lastDecryptedMessage;
     lm.lastMessageData = "";
     lm.lastMessageURI = null;
     lm.lastStatus = {};
-  }
+  },
 };
 
 EnigmailSingletons.clearLastDecryptedMessage();
--- a/mail/extensions/openpgp/content/modules/socks5Proxy.jsm
+++ b/mail/extensions/openpgp/content/modules/socks5Proxy.jsm
@@ -3,113 +3,120 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailSocks5Proxy"];
 
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+
 const CC = Components.Constructor;
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const getEnigmailPrefs = EnigmailLazy.loader("enigmail/prefs.jsm", "EnigmailPrefs");
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLazy = ChromeUtils.import(
+  "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const getEnigmailPrefs = EnigmailLazy.loader(
+  "enigmail/prefs.jsm",
+  "EnigmailPrefs"
+);
 
 const CHECK_TOR_URI = "https://check.torproject.org/api/ip";
-const EXPECTED_TOR_EXISTS_RESPONSE = "\"IsTor\":true";
+const EXPECTED_TOR_EXISTS_RESPONSE = '"IsTor":true';
 const TOR_IP_ADDR_PREF = "torIpAddr";
 
-const CONNECTION_FLAGS = 0;
-const SECONDS_TO_WAIT_FOR_CONNECTION = -1;
-
 function createCheckTorURIChannel() {
   EnigmailLog.DEBUG("socks5proxy.jsm: createCheckTorURIChannel()\n");
-  const ioservice = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
-  return ioservice.newChannel2(CHECK_TOR_URI, "UTF-8", null, null, null, null, null, null);
-}
-
-function protocolProxyService() {
-  return Cc["@mozilla.org/network/protocol-proxy-service;1"].getService(Ci.nsIProtocolProxyService);
+  const ioservice = Services.io;
+  return ioservice.newChannel2(
+    CHECK_TOR_URI,
+    "UTF-8",
+    null,
+    null,
+    null,
+    null,
+    null,
+    null
+  );
 }
 
 function createScriptableInputStream(inputStream) {
-  return CC("@mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream", "init")(inputStream);
+  return CC(
+    "@mozilla.org/scriptableinputstream;1",
+    "nsIScriptableInputStream",
+    "init"
+  )(inputStream);
 }
 
 function buildListener(hasFoundTor, isDoneChecking) {
   EnigmailLog.DEBUG("socks5proxy.jsm: buildListener()\n");
   let listener = {
-    onStartRequest: function(request) {},
-    onStopRequest: function(request, statusCode) {
+    onStartRequest(request) {},
+    onStopRequest(request, statusCode) {
       isDoneChecking();
     },
-    QueryInterface: EnigmailCompat.generateQI(["nsIRequestObserver", "nsIStreamListener"])
+    QueryInterface: EnigmailCompat.generateQI([
+      "nsIRequestObserver",
+      "nsIStreamListener",
+    ]),
   };
 
   listener.onDataAvailable = function(request, inputStream, offset, count) {
     const response = createScriptableInputStream(inputStream).read(count);
-    hasFoundTor(response.indexOf(EXPECTED_TOR_EXISTS_RESPONSE) !== -1);
+    hasFoundTor(response.includes(EXPECTED_TOR_EXISTS_RESPONSE));
   };
 
   return listener;
 }
 
 function getCurrentThread() {
-  return Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager).currentThread;
-}
-
-function filterWith(portPref) {
-  EnigmailLog.DEBUG("socks5proxy.jsm: filterWith()\n");
-
-  const port = getEnigmailPrefs().getPref(portPref);
-  const failoverProxy = null;
-  return {
-    applyFilter: function(proxyService, uri, proxyInfo) {
-      return proxyService.newProxyInfo("socks", getEnigmailPrefs().getPref(TOR_IP_ADDR_PREF), port, CONNECTION_FLAGS, SECONDS_TO_WAIT_FOR_CONNECTION, failoverProxy);
-    },
-    QueryInterface: EnigmailCompat.generateQI(["nsIProtocolProxyFilter"])
-  };
+  return Services.tm.currentThread;
 }
 
 /**
  * Checks if Tor is running
  *
  * @param portPref - string: the preferences key of either torServicePort or torBrowserBundlePort
  *
  * @return true if a running Tor service has been found, false otherwise
  */
 function checkTorExists(portPref) {
   EnigmailLog.DEBUG("socks5proxy.jsm: checkTorExists()\n");
-  const pps = protocolProxyService().registerFilter(filterWith(portPref), 1);
 
   let doneCheckingTor = false;
   let foundTor = false;
 
   function isDoneChecking() {
     doneCheckingTor = true;
   }
 
   function hasFoundTor(val) {
     foundTor = val;
   }
 
   const listener = buildListener(hasFoundTor, isDoneChecking);
 
   const sharedContext = null;
-  const ioservice = createCheckTorURIChannel().asyncOpen(listener, sharedContext);
+  createCheckTorURIChannel().asyncOpen(listener, sharedContext);
   const currentThread = getCurrentThread();
 
   while (!doneCheckingTor) {
     currentThread.processNextEvent(true);
   }
 
   return foundTor;
 }
 
 var EnigmailSocks5Proxy = {
-  checkTorExists: checkTorExists,
-  torIpAddr: function() {
+  checkTorExists,
+  torIpAddr() {
     EnigmailLog.DEBUG("socks5proxy.jsm: torIpAddr()\n");
     return getEnigmailPrefs().getPref(TOR_IP_ADDR_PREF);
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/sqliteDb.jsm
+++ b/mail/extensions/openpgp/content/modules/sqliteDb.jsm
@@ -5,189 +5,195 @@
 "use strict";
 
 /**
  *  Module that provides generic functions for the Enigmail SQLite database
  */
 
 var EXPORTED_SYMBOLS = ["EnigmailSqliteDb"];
 
-
-
-const Cr = Components.results;
-
-
 const Sqlite = ChromeUtils.import("resource://gre/modules/Sqlite.jsm").Sqlite;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
+const EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
 
 var EnigmailSqliteDb = {
   /**
    * Provide an sqlite conection object asynchronously, retrying if needed
    *
    * @return {Promise<Sqlite Connection>}: the Sqlite database object
    */
 
-  openDatabase: function() {
+  openDatabase() {
     EnigmailLog.DEBUG("sqliteDb.jsm: openDatabase()\n");
     return new Promise((resolve, reject) => {
       openDatabaseConn(resolve, reject, 100, Date.now() + 10000);
     });
   },
 
-  checkDatabaseStructure: async function() {
+  async checkDatabaseStructure() {
     EnigmailLog.DEBUG(`sqliteDb.jsm: checkDatabaseStructure()\n`);
     let conn;
     try {
       conn = await this.openDatabase();
       await checkAutocryptTable(conn);
       await checkWkdTable(conn);
       conn.close();
       EnigmailLog.DEBUG(`sqliteDb.jsm: checkDatabaseStructure - success\n`);
-    }
-    catch (ex) {
+    } catch (ex) {
       EnigmailLog.ERROR(`sqliteDb.jsm: checkDatabaseStructure: ERROR: ${ex}\n`);
       if (conn) {
         conn.close();
       }
     }
-  }
+  },
 };
 
-
 /**
  * use a promise to open the Enigmail database.
  *
  * it's possible that there will be an NS_ERROR_STORAGE_BUSY
  * so we're willing to retry for a little while.
  *
  * @param {function} resolve: function to call when promise succeeds
  * @param {function} reject:  function to call when promise fails
  * @param {Number}   waitms:  Integer - number of milliseconds to wait before trying again in case of NS_ERROR_STORAGE_BUSY
  * @param {Number}   maxtime: Integer - unix epoch (in milliseconds) of the point at which we should give up.
  */
 function openDatabaseConn(resolve, reject, waitms, maxtime) {
   EnigmailLog.DEBUG("sqliteDb.jsm: openDatabaseConn()\n");
   Sqlite.openConnection({
     path: "enigmail.sqlite",
-    sharedMemoryCache: false
-  }).
-  then(connection => {
-    resolve(connection);
-  }).
-  catch(error => {
-    let now = Date.now();
-    if (now > maxtime) {
-      reject(error);
-      return;
-    }
-    EnigmailTimer.setTimeout(function() {
-      openDatabaseConn(resolve, reject, waitms, maxtime);
-    }, waitms);
-  });
+    sharedMemoryCache: false,
+  })
+    .then(connection => {
+      resolve(connection);
+    })
+    .catch(error => {
+      let now = Date.now();
+      if (now > maxtime) {
+        reject(error);
+        return;
+      }
+      EnigmailTimer.setTimeout(function() {
+        openDatabaseConn(resolve, reject, waitms, maxtime);
+      }, waitms);
+    });
 }
 
-
 /**
  * Ensure that the database structure matches the latest version
  * (table is available)
  *
  * @param connection: Object - SQLite connection
  *
  * @return {Promise<Boolean>}
  */
 async function checkAutocryptTable(connection) {
   try {
     let exists = await connection.tableExists("autocrypt_keydata");
     EnigmailLog.DEBUG("sqliteDB.jsm: checkAutocryptTable - success\n");
     if (!exists) {
       await createAutocryptTable(connection);
-    }
-    else {
+    } else {
       let hasKeyRingInserted = false;
-      await connection.execute("pragma table_info('autocrypt_keydata');", {},
-        function _onRow(row) {
+      await connection.execute(
+        "pragma table_info('autocrypt_keydata');",
+        {},
+        function(row) {
           let colname = row.getResultByName("name");
-          if (colname === "keyring_inserted") hasKeyRingInserted = true;
-        });
-      if (hasKeyRingInserted) return true;
+          if (colname === "keyring_inserted") {
+            hasKeyRingInserted = true;
+          }
+        }
+      );
+      if (hasKeyRingInserted) {
+        return true;
+      }
 
-      await connection.execute("alter table autocrypt_keydata add keyring_inserted text default '0';", {},
-        function _onRow(row) {});
-      let EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
+      await connection.execute(
+        "alter table autocrypt_keydata add keyring_inserted text default '0';",
+        {},
+        function(row) {}
+      );
+      let EnigmailAutocrypt = ChromeUtils.import(
+        "chrome://openpgp/content/modules/autocrypt.jsm"
+      ).EnigmailAutocrypt;
       EnigmailAutocrypt.updateAllImportedKeys();
     }
-  }
-  catch (error) {
+  } catch (error) {
     EnigmailLog.DEBUG(`sqliteDB.jsm: checkAutocryptTable - error ${error}\n`);
     throw error;
   }
 
   return true;
 }
 /**
  * Create the "autocrypt_keydata" table and the corresponding index
  *
  * @param connection: Object - SQLite connection
  *
  * @return {Promise}
  */
 async function createAutocryptTable(connection) {
   EnigmailLog.DEBUG("sqliteDB.jsm: createAutocryptTable()\n");
 
-  await connection.execute("create table autocrypt_keydata (" +
+  await connection.execute(
+    "create table autocrypt_keydata (" +
     "email text not null, " + // email address of correspondent
     "keydata text not null, " + // base64-encoded key as received
     "fpr text, " + // fingerprint of key
     "type text not null, " + // key type (1==OpenPGP, regular key. 1g == OpenPGP gossip)
     "last_seen_autocrypt text, " +
     "last_seen text not null, " +
     "state text not null," + // timestamp of last mail received for the email/type combination
-    "keyring_inserted text default '0');"
+      "keyring_inserted text default '0');"
   );
 
   EnigmailLog.DEBUG("sqliteDB.jsm: createAutocryptTable - index\n");
-  await connection.execute("create unique index autocrypt_keydata_i1 on autocrypt_keydata(email, type)");
+  await connection.execute(
+    "create unique index autocrypt_keydata_i1 on autocrypt_keydata(email, type)"
+  );
 
   return null;
 }
 
-
-
 /**
  * Ensure that the database has the wkd_lookup_timestamp table.
  *
  * @param connection: Object - SQLite connection
  *
  * @return Promise
  */
 async function checkWkdTable(connection) {
   EnigmailLog.DEBUG("sqliteDB.jsm: checkWkdTable()\n");
 
   try {
     let exists = await connection.tableExists("wkd_lookup_timestamp");
     EnigmailLog.DEBUG("sqliteDB.jsm: checkWkdTable - success\n");
     if (!exists) {
       await createWkdTable(connection);
     }
-  }
-  catch (error) {
+  } catch (error) {
     EnigmailLog.DEBUG("sqliteDB.jsm: checkWkdTable - error\n");
-    throw (error);
+    throw error;
   }
 }
 
 /**
  * Create the "wkd_lookup_timestamp" table.
  *
  * @param connection: Object - SQLite connection
  *
  * @return Promise
  */
 function createWkdTable(connection) {
   EnigmailLog.DEBUG("sqliteDB.jsm: createWkdTable()\n");
 
   return connection.execute(
     "create table wkd_lookup_timestamp (" +
     "email text not null primary key, " + // email address of correspondent
-    "last_seen integer);"); // timestamp of last mail received for the email/type combination
+      "last_seen integer);"
+  ); // timestamp of last mail received for the email/type combination
 }
--- a/mail/extensions/openpgp/content/modules/stdlib.jsm
+++ b/mail/extensions/openpgp/content/modules/stdlib.jsm
@@ -3,32 +3,31 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 /**
  * Wrapper library for TB-stdlib to avoid naming conflicts
  */
 
-
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailStdlib"];
 
 const {
   composeInIframe,
   getEditorForIframe,
   citeString,
   htmlToPlainText,
   simpleWrap,
   plainTextToHtml,
   replyAllParams,
   determineComposeHtml,
   composeMessageTo,
-  getSignatureContentsForAccount
+  getSignatureContentsForAccount,
 } = ChromeUtils.import("chrome://openpgp/content/modules/stdlib/compose.jsm");
 
 const {
   gIdentities,
   fillIdentities,
   getIdentities,
   getDefaultIdentity,
   getIdentityForEmail,
@@ -41,17 +40,17 @@ const {
   escapeHtml,
   sanitize,
   parseMimeLine,
   encodeUrlParameters,
   decodeUrlParameters,
   systemCharset,
   isOSX,
   isWindows,
-  isAccel
+  isAccel,
 } = ChromeUtils.import("chrome://openpgp/content/modules/stdlib/misc.jsm");
 
 const {
   msgHdrToMessageBody,
   msgHdrToNeckoURL,
   msgHdrGetTags,
   msgUriToMsgHdr,
   msgHdrGetUri,
@@ -64,68 +63,70 @@ const {
   msgHdrIsRss,
   msgHdrIsNntp,
   msgHdrIsJunk,
   msgHdrsMarkAsRead,
   msgHdrsArchive,
   msgHdrsDelete,
   getMail3Pane,
   msgHdrGetHeaders,
-  msgHdrsModifyRaw
-} = ChromeUtils.import("chrome://openpgp/content/modules/stdlib/msgHdrUtils.jsm");
+  msgHdrsModifyRaw,
+} = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib/msgHdrUtils.jsm"
+);
 
 var EnigmailStdlib = {
   // compose.jsm
-  'composeInIframe': composeInIframe,
-  'getEditorForIframe': getEditorForIframe,
-  'citeString': citeString,
-  'htmlToPlainText': htmlToPlainText,
-  'simpleWrap': simpleWrap,
-  'plainTextToHtml': plainTextToHtml,
-  'replyAllParams': replyAllParams,
-  'determineComposeHtml': determineComposeHtml,
-  'composeMessageTo': composeMessageTo,
-  'getSignatureContentsForAccount': getSignatureContentsForAccount,
+  composeInIframe,
+  getEditorForIframe,
+  citeString,
+  htmlToPlainText,
+  simpleWrap,
+  plainTextToHtml,
+  replyAllParams,
+  determineComposeHtml,
+  composeMessageTo,
+  getSignatureContentsForAccount,
 
   // misc.jsm
-  'gIdentities': gIdentities,
-  'fillIdentities': fillIdentities,
-  'getIdentities': getIdentities,
-  'getDefaultIdentity': getDefaultIdentity,
-  'getIdentityForEmail': getIdentityForEmail,
-  'hasConfiguredAccounts': hasConfiguredAccounts,
-  'range': range,
-  'MixIn': MixIn,
-  'combine': combine,
-  'entries': entries,
-  'dateAsInMessageList': dateAsInMessageList,
-  'escapeHtml': escapeHtml,
-  'sanitize': sanitize,
-  'parseMimeLine': parseMimeLine,
-  'encodeUrlParameters': encodeUrlParameters,
-  'decodeUrlParameters': decodeUrlParameters,
-  'systemCharset': systemCharset,
-  'isOSX': isOSX,
-  'isWindows': isWindows,
-  'isAccel': isAccel,
+  gIdentities,
+  fillIdentities,
+  getIdentities,
+  getDefaultIdentity,
+  getIdentityForEmail,
+  hasConfiguredAccounts,
+  range,
+  MixIn,
+  combine,
+  entries,
+  dateAsInMessageList,
+  escapeHtml,
+  sanitize,
+  parseMimeLine,
+  encodeUrlParameters,
+  decodeUrlParameters,
+  systemCharset,
+  isOSX,
+  isWindows,
+  isAccel,
 
   // msgHdrUtils.jsm
-  'msgHdrToMessageBody': msgHdrToMessageBody,
-  'msgHdrToNeckoURL': msgHdrToNeckoURL,
-  'msgHdrGetTags': msgHdrGetTags,
-  'msgUriToMsgHdr': msgUriToMsgHdr,
-  'msgHdrGetUri': msgHdrGetUri,
-  'msgHdrFromNeckoUrl': msgHdrFromNeckoUrl,
-  'msgHdrSetTags': msgHdrSetTags,
-  'msgHdrIsDraft': msgHdrIsDraft,
-  'msgHdrIsSent': msgHdrIsSent,
-  'msgHdrIsArchive': msgHdrIsArchive,
-  'msgHdrIsInbox': msgHdrIsInbox,
-  'msgHdrIsRss': msgHdrIsRss,
-  'msgHdrIsNntp': msgHdrIsNntp,
-  'msgHdrIsJunk': msgHdrIsJunk,
-  'msgHdrsMarkAsRead': msgHdrsMarkAsRead,
-  'msgHdrsArchive': msgHdrsArchive,
-  'msgHdrsDelete': msgHdrsDelete,
-  'getMail3Pane': getMail3Pane,
-  'msgHdrGetHeaders': msgHdrGetHeaders,
-  'msgHdrsModifyRaw': msgHdrsModifyRaw
-};
\ No newline at end of file
+  msgHdrToMessageBody,
+  msgHdrToNeckoURL,
+  msgHdrGetTags,
+  msgUriToMsgHdr,
+  msgHdrGetUri,
+  msgHdrFromNeckoUrl,
+  msgHdrSetTags,
+  msgHdrIsDraft,
+  msgHdrIsSent,
+  msgHdrIsArchive,
+  msgHdrIsInbox,
+  msgHdrIsRss,
+  msgHdrIsNntp,
+  msgHdrIsJunk,
+  msgHdrsMarkAsRead,
+  msgHdrsArchive,
+  msgHdrsDelete,
+  getMail3Pane,
+  msgHdrGetHeaders,
+  msgHdrsModifyRaw,
+};
--- a/mail/extensions/openpgp/content/modules/stdlib/compose.jsm
+++ b/mail/extensions/openpgp/content/modules/stdlib/compose.jsm
@@ -4,142 +4,122 @@
 
 /**
  * @fileoverview Composition-related utils: quoting, wrapping text before
  *  sending a message, converting back and forth between HTML and plain text...
  * @author Jonathan Protzenko
  */
 
 var EXPORTED_SYMBOLS = [
-  'composeInIframe', 'getEditorForIframe',
-  'quoteMsgHdr', 'citeString',
-  'htmlToPlainText', 'simpleWrap',
-  'plainTextToHtml', 'replyAllParams',
-  'determineComposeHtml', 'composeMessageTo',
-  'getSignatureContentsForAccount',
-]
+  "composeInIframe",
+  "getEditorForIframe",
+  "quoteMsgHdr",
+  "citeString",
+  "htmlToPlainText",
+  "simpleWrap",
+  "plainTextToHtml",
+  "replyAllParams",
+  "determineComposeHtml",
+  "composeMessageTo",
+  "getSignatureContentsForAccount",
+];
 
-const {
-  results: Cr
-} = Components;
-
-const {
-  MsgHdrToMimeMessage,
-  MimeMessage, MimeContainer,
-  MimeBody, MimeUnknown,
-  MimeMessageAttachment
-} = ChromeUtils.import("resource:///modules/gloda/MimeMessage.jsm");
-
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 var MailServices;
 try {
-  MailServices = ChromeUtils.import("resource:///modules/MailServices.jsm").MailServices;
-}
-catch (x){
-  MailServices = ChromeUtils.import("resource:///modules/mailServices.js").MailServices;
+  MailServices = ChromeUtils.import("resource:///modules/MailServices.jsm")
+    .MailServices;
+} catch (x) {
+  MailServices = ChromeUtils.import("resource:///modules/mailServices.js")
+    .MailServices;
 }
 
 const {
-  gIdentities,
-  fillIdentities,
   getIdentities,
   getDefaultIdentity,
-  getIdentityForEmail,
-  hasConfiguredAccounts,
-  range,
-  MixIn,
   combine,
-  entries,
-  dateAsInMessageList,
   escapeHtml,
-  sanitize,
-  parseMimeLine,
-  encodeUrlParameters,
-  decodeUrlParameters,
   systemCharset,
-  isOSX,
-  isWindows,
-  isAccel
 } = ChromeUtils.import("chrome://openpgp/content/modules/stdlib/misc.jsm");
 
-const {
-  msgHdrToMessageBody,
-  msgHdrToNeckoURL,
-  msgHdrGetTags,
-  msgUriToMsgHdr,
-  msgHdrGetUri,
-  msgHdrFromNeckoUrl,
-  msgHdrSetTags,
-  msgHdrIsDraft,
-  msgHdrIsSent,
-  msgHdrIsArchive,
-  msgHdrIsInbox,
-  msgHdrIsRss,
-  msgHdrIsNntp,
-  msgHdrIsJunk,
-  msgHdrsMarkAsRead,
-  msgHdrsArchive,
-  msgHdrsDelete,
-  getMail3Pane,
-  msgHdrGetHeaders,
-  msgHdrsModifyRaw
-} = ChromeUtils.import("chrome://openpgp/content/modules/stdlib/msgHdrUtils.jsm");
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
+const { msgHdrGetUri, getMail3Pane, msgHdrGetHeaders } = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib/msgHdrUtils.jsm"
+);
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
 
 function getEditorForIframe(aIframe) {
   let w = aIframe.contentWindow;
-  let s = w.QueryInterface(Ci.nsIInterfaceRequestor)
+  let s = w
+    .QueryInterface(Ci.nsIInterfaceRequestor)
     .getInterface(Ci.nsIWebNavigation)
     .QueryInterface(Ci.nsIInterfaceRequestor)
     .getInterface(Ci.nsIEditingSession);
   return s.getEditorForWindow(w);
 }
 
-function composeInIframe(aIframe, {
-  msgHdr,
-  compType,
-  identity,
-}) {
-  let fields = Cc["@mozilla.org/messengercompose/composefields;1"]
-    .createInstance(Ci.nsIMsgCompFields);
-  let params = Cc["@mozilla.org/messengercompose/composeparams;1"]
-    .createInstance(Ci.nsIMsgComposeParams);
+function composeInIframe(aIframe, { msgHdr, compType, identity }) {
+  let fields = Cc[
+    "@mozilla.org/messengercompose/composefields;1"
+  ].createInstance(Ci.nsIMsgCompFields);
+  let params = Cc[
+    "@mozilla.org/messengercompose/composeparams;1"
+  ].createInstance(Ci.nsIMsgComposeParams);
   params.identity = identity;
   if (msgHdr) {
     params.origMsgHdr = msgHdr;
     params.originalMsgURI = msgHdrGetUri(msgHdr);
   }
   params.composeFields = fields;
   params.type = compType;
 
-  let compose = MailServices.compose.initCompose(params, getMail3Pane(), aIframe.docShell);
-  EnigmailLog.DEBUG("editor= " + getEditorForIframe(aIframe).toString() + ", iframe= " + aIframe.toString() + "\n");
+  let compose = MailServices.compose.initCompose(
+    params,
+    getMail3Pane(),
+    aIframe.docShell
+  );
+  EnigmailLog.DEBUG(
+    "editor= " +
+      getEditorForIframe(aIframe).toString() +
+      ", iframe= " +
+      aIframe.toString() +
+      "\n"
+  );
   compose.initEditor(getEditorForIframe(aIframe), aIframe.contentWindow);
 }
 
 /**
  * A function that properly quotes a plaintext email.
  * @param {String} aStr The mail body that we're expected to quote.
  * @return {String} The quoted mail body with &gt;'s properly taken care of.
  */
 function citeString(aStr) {
   let l = aStr.length;
-  return aStr.replace("\n", function(match, offset, str) {
-    // http://mxr.mozilla.org/comm-central/source/mozilla/editor/libeditor/text/nsInternetCiter.cpp#96
-    if (offset < l - 1) {
-      if (str[offset + 1] != ">" && str[offset + 1] != "\n" && str[offset + 1] != "\r")
-        return "\n> ";
-      else
+  return aStr.replace(
+    "\n",
+    function(match, offset, str) {
+      // http://mxr.mozilla.org/comm-central/source/mozilla/editor/libeditor/text/nsInternetCiter.cpp#96
+      if (offset < l - 1) {
+        if (
+          str[offset + 1] != ">" &&
+          str[offset + 1] != "\n" &&
+          str[offset + 1] != "\r"
+        ) {
+          return "\n> ";
+        }
         return "\n>";
-    }
-    else {
+      }
+
       return match;
-    }
-  }, "g");
+    },
+    "g"
+  );
 }
 
 /**
  * Wrap some text. Beware, that function doesn't do rewrapping, and only
  *  operates on non-quoted lines. This is only useful in our very specific case
  *  where the quoted lines have been properly wrapped for format=flowed already,
  *  and the non-quoted lines are the only ones that need wrapping for
  *  format=flowed.
@@ -149,72 +129,78 @@ function citeString(aStr) {
  * This function, when breaking lines, will do space-stuffing per the RFC if
  *  after the break the text starts with From or &gt;.
  * @param {String} txt The text that should be wrapped.
  * @param {Number} width (optional) The width we should wrap to. Default to 72.
  * @return {String} The text with non-quoted lines wrapped. This is suitable for
  *  sending as format=flowed.
  */
 function simpleWrap(txt, width) {
-  if (!width)
+  if (!width) {
     width = 72;
+  }
 
   function maybeEscape(line) {
-    if (line.indexOf("From") === 0 || line.indexOf(">") === 0)
-      return (" " + line);
-    else
-      return line;
+    if (line.indexOf("From") === 0 || line.indexOf(">") === 0) {
+      return " " + line;
+    }
+    return line;
   }
 
   /**
    * That function takes a (long) line, and splits it into many lines.
    * @param soFar {Array String} an accumulator of the lines we've wrapped already
    * @param remaining {String} the remaining string to wrap
    */
   function splitLongLine(soFar, remaining) {
     if (remaining.length > width) {
       // Start at the end of the line, and move back until we find a word
       // boundary.
       let i = width - 1;
-      while (remaining[i] != " " && i > 0)
+      while (remaining[i] != " " && i > 0) {
         i--;
+      }
       // We found a word boundary, break there
       if (i > 0) {
         // This includes the trailing space that indicates that we are wrapping
         //  a long line with format=flowed.
         soFar.push(maybeEscape(remaining.substring(0, i + 1)));
-        return splitLongLine(soFar, remaining.substring(i + 1, remaining.length));
+        return splitLongLine(
+          soFar,
+          remaining.substring(i + 1, remaining.length)
+        );
       }
-      else {
-        // No word boundary, break at the first space
-        let j = remaining.indexOf(" ");
-        if (j > 0) {
-          // Same remark about the trailing space.
-          soFar.push(maybeEscape(remaining.substring(0, j + 1)));
-          return splitLongLine(soFar, remaining.substring(j + 1, remaining.length));
-        }
-        else {
-          // Make sure no one interprets this as a line continuation.
-          soFar.push(remaining.trimRight());
-          return soFar.join("\n");
-        }
+
+      // No word boundary, break at the first space
+      let j = remaining.indexOf(" ");
+      if (j > 0) {
+        // Same remark about the trailing space.
+        soFar.push(maybeEscape(remaining.substring(0, j + 1)));
+        return splitLongLine(
+          soFar,
+          remaining.substring(j + 1, remaining.length)
+        );
       }
-    }
-    else {
-      // Same remark about the trailing space.
-      soFar.push(maybeEscape(remaining.trimRight()));
+
+      // Make sure no one interprets this as a line continuation.
+      soFar.push(remaining.trimRight());
       return soFar.join("\n");
     }
+
+    // Same remark about the trailing space.
+    soFar.push(maybeEscape(remaining.trimRight()));
+    return soFar.join("\n");
   }
 
   let lines = txt.split(/\r?\n/);
 
   lines.forEach(function(line, i) {
-    if (line.length > width && line[0] != ">")
+    if (line.length > width && line[0] != ">") {
       lines[i] = splitLongLine([], line);
+    }
   });
   return lines.join("\n");
 }
 
 /**
  * Convert HTML into text/plain suitable for insertion right away in the mail
  *  body. If there is text with &gt;'s at the beginning of lines, these will be
  *  space-stuffed, and the same goes for Froms. &lt;blockquote&gt;s will be converted
@@ -226,147 +212,162 @@ function simpleWrap(txt, width) {
  *  course).
  * @param {String} aHtml A string containing the HTML that's to be converted.
  * @return {String} A text/plain string suitable for insertion in a mail body.
  */
 function htmlToPlainText(aHtml) {
   // Yes, this is ridiculous, we're instanciating composition fields just so
   //  that they call ConvertBufPlainText for us. But ConvertBufToPlainText
   //  really isn't easily scriptable, so...
-  let fields = Cc["@mozilla.org/messengercompose/composefields;1"]
-    .createInstance(Ci.nsIMsgCompFields);
+  let fields = Cc[
+    "@mozilla.org/messengercompose/composefields;1"
+  ].createInstance(Ci.nsIMsgCompFields);
   fields.body = aHtml;
   fields.forcePlainText = true;
   fields.ConvertBodyToPlainText();
   return fields.body;
 }
 
 /**
  * @ignore
  */
 function citeLevel(line) {
-  let i;
-  for (i = 0; line[i] == ">" && i < line.length; ++i)
-  ; // nop
+  let i = 0;
+  while (line[i] == ">" && i < line.length) {
+    ++i;
+  } // nop
   return i;
-};
+}
 
 /**
  * Just try to convert quoted lines back to HTML markup (&lt;blockquote&gt;s).
  * @param {String} txt
  * @return {String}
  */
 function plainTextToHtml(txt) {
   let lines = txt.split(/\r?\n/);
   let newLines = [];
   let level = 0;
   for (let line of lines) {
     let newLevel = citeLevel(line);
-    if (newLevel > level)
-      for (let i = level; i < newLevel; ++i)
+    if (newLevel > level) {
+      for (let i = level; i < newLevel; ++i) {
         newLines.push('<blockquote type="cite">');
-    if (newLevel < level)
-      for (let i = newLevel; i < level; ++i)
-        newLines.push('</blockquote>');
-    let newLine = line[newLevel] == " " ? escapeHtml(line.substring(newLevel + 1, line.length)) : escapeHtml(line.substring(newLevel, line.length));
+      }
+    }
+    if (newLevel < level) {
+      for (let i = newLevel; i < level; ++i) {
+        newLines.push("</blockquote>");
+      }
+    }
+    let newLine =
+      line[newLevel] == " "
+        ? escapeHtml(line.substring(newLevel + 1, line.length))
+        : escapeHtml(line.substring(newLevel, line.length));
     newLines.push(newLine);
     level = newLevel;
   }
   return newLines.join("\n");
 }
 
 function parse(aMimeLine) {
-  if (!aMimeLine)
-    return [
-      [],
-      []
-    ];
+  if (!aMimeLine) {
+    return [[], []];
+  }
   let emails = {};
   let fullNames = {};
   let names = {};
-  let numAddresses = MailServices.headerParser.parseHeadersWithArray(aMimeLine, emails, names, fullNames);
+  MailServices.headerParser.parseHeadersWithArray(
+    aMimeLine,
+    emails,
+    names,
+    fullNames
+  );
   return [names.value, emails.value];
 }
 
 /**
  * Analyze a message header, and then return all the compose parameters for the
  * reply-all case.
  * @param {nsIIdentity} The identity you've picked for the reply.
  * @param {nsIMsgDbHdr} The message header.
  * @param {k} The function to call once we've determined all parameters. Take an
  *  argument like
  *  {{ to: [[name, email]], cc: [[name, email]], bcc: [[name, email]]}}
  */
 function replyAllParams(aIdentity, aMsgHdr, k) {
   // Do the whole shebang to find out who to send to...
-  let [
-    [author],
-    [authorEmailAddress]
-  ] = parse(aMsgHdr.author);
+  let [[author], [authorEmailAddress]] = parse(aMsgHdr.author);
   let [recipients, recipientsEmailAddresses] = parse(aMsgHdr.recipients);
   let [ccList, ccListEmailAddresses] = parse(aMsgHdr.ccList);
   let [bccList, bccListEmailAddresses] = parse(aMsgHdr.bccList);
   authorEmailAddress = authorEmailAddress.toLowerCase();
   recipientsEmailAddresses = recipientsEmailAddresses.map(x => x.toLowerCase());
   ccListEmailAddresses = ccListEmailAddresses.map(x => x.toLowerCase());
   bccListEmailAddresses = bccListEmailAddresses.map(x => x.toLowerCase());
   let identity = aIdentity;
   let identityEmail = identity.email.toLowerCase();
   let to = [],
     cc = [],
     bcc = [];
 
   let isReplyToOwnMsg = false;
   for (let currentIdentity of getIdentities()) {
     let email = currentIdentity.identity.email.toLowerCase();
-    if (email == authorEmailAddress)
+    if (email == authorEmailAddress) {
       isReplyToOwnMsg = true;
-    if (recipientsEmailAddresses.some(x => x == email))
+    }
+    if (recipientsEmailAddresses.some(x => x == email)) {
       isReplyToOwnMsg = false;
-    if (ccListEmailAddresses.some(x => x == email))
+    }
+    if (ccListEmailAddresses.some(x => x == email)) {
       isReplyToOwnMsg = false;
+    }
   }
 
   // Actually we are implementing the "Reply all" logic... that's better, no one
   //  wants to really use reply anyway
   if (isReplyToOwnMsg) {
     to = recipients.map((r, i) => [r, recipientsEmailAddresses[i]]);
+  } else {
+    to = [[author, authorEmailAddress]];
   }
-  else {
-    to = [
-      [author, authorEmailAddress]
-    ];
-  }
-  cc = ccList.map((cc, i) => [cc, ccListEmailAddresses[i]]).
-  filter((e, i) => e[1] != identityEmail);
+  cc = ccList
+    .map((cc, i) => [cc, ccListEmailAddresses[i]])
+    .filter((e, i) => e[1] != identityEmail);
   if (!isReplyToOwnMsg) {
-    cc = cc.concat(recipients.map((r, i) => [r, recipientsEmailAddresses[i]]).filter((e, i) => e[1] != identityEmail));
+    cc = cc.concat(
+      recipients
+        .map((r, i) => [r, recipientsEmailAddresses[i]])
+        .filter((e, i) => e[1] != identityEmail)
+    );
   }
   bcc = bccList.map((bcc, i) => [bcc, bccListEmailAddresses]);
 
   let finish = function(to, cc, bcc) {
     let hashMap = {};
-    for (let [name, email] of to)
+    for (let [email] of to) {
       hashMap[email] = null;
+    }
     cc = cc.filter(function([name, email]) {
-      let r = (email in hashMap);
+      let r = email in hashMap;
       hashMap[email] = null;
-      return !r
+      return !r;
     });
     bcc = bcc.filter(function([name, email]) {
-      let r = (email in hashMap);
+      let r = email in hashMap;
       hashMap[email] = null;
-      return !r
+      return !r;
     });
     k({
-      to: to,
-      cc: cc,
-      bcc: bcc
+      to,
+      cc,
+      bcc,
     });
-  }
+  };
 
   // Do we have a Reply-To header?
   msgHdrGetHeaders(aMsgHdr, function(aHeaders) {
     if (aHeaders.has("reply-to")) {
       let [names, emails] = parse(aHeaders.get("reply-to"));
       emails = emails.map(email => email.toLowerCase());
       if (emails.length) {
         // Invariant: at this stage, we only have one item in to.
@@ -383,93 +384,100 @@ function replyAllParams(aIdentity, aMsgH
  * marked as [noscript], just to make our lives complicated. [insert random rant
  * here].
  *
  * @param aIdentity (optional) You can specify the identity which you would like
  * to get the preference for.
  * @return a bool which is true if you should compose in HTML
  */
 function determineComposeHtml(aIdentity) {
-  if (!aIdentity)
+  if (!aIdentity) {
     aIdentity = getDefaultIdentity().identity;
+  }
 
   if (aIdentity) {
-    return (aIdentity.composeHtml == Ci.nsIMsgCompFormat.HTML);
+    return aIdentity.composeHtml == Ci.nsIMsgCompFormat.HTML;
   }
-  else {
-    return Cc["@mozilla.org/preferences-service;1"]
-      .getService(Ci.nsIPrefService)
-      .getBranch(null)
-      .getBoolPref("mail.compose_html");
-  }
+
+  return Services.prefs.getBranch(null).getBoolPref("mail.compose_html");
 }
 
 /**
  * Open a composition window for the given email address.
  * @param aEmail {String}
  * @param aDisplayedFolder {nsIMsgFolder} pass gFolderDisplay.displayedFolder
  */
 function composeMessageTo(aEmail, aDisplayedFolder) {
-  let fields = Cc["@mozilla.org/messengercompose/composefields;1"]
-    .createInstance(Ci.nsIMsgCompFields);
-  let params = Cc["@mozilla.org/messengercompose/composeparams;1"]
-    .createInstance(Ci.nsIMsgComposeParams);
-  fields.to = aEmail
+  let fields = Cc[
+    "@mozilla.org/messengercompose/composefields;1"
+  ].createInstance(Ci.nsIMsgCompFields);
+  let params = Cc[
+    "@mozilla.org/messengercompose/composeparams;1"
+  ].createInstance(Ci.nsIMsgComposeParams);
+  fields.to = aEmail;
   params.type = Ci.nsIMsgCompType.New;
   params.format = Ci.nsIMsgCompFormat.Default;
   if (aDisplayedFolder) {
-    params.identity = MailServices.accounts
-      .getFirstIdentityForServer(aDisplayedFolder.server);
+    params.identity = MailServices.accounts.getFirstIdentityForServer(
+      aDisplayedFolder.server
+    );
   }
   params.composeFields = fields;
   MailServices.compose.OpenComposeWindowWithParams(null, params);
 }
 
 /**
  * Returns signature contents depending on account settings of the identity.
  * HTML signature is converted to plain text.
  * @param {nsIIdentity} The identity you've picked for the reply.
  * @return {String} plain text signature
  */
 function getSignatureContentsForAccount(aIdentity) {
   let signature = "";
-  if (!aIdentity)
+  if (!aIdentity) {
     return signature;
+  }
 
   if (aIdentity.attachSignature && aIdentity.signature) {
     let charset = systemCharset();
     const replacementChar =
       Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
-    let fstream = Cc["@mozilla.org/network/file-input-stream;1"]
-      .createInstance(Ci.nsIFileInputStream);
-    let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"]
-      .createInstance(Ci.nsIConverterInputStream);
+    let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
+      Ci.nsIFileInputStream
+    );
+    let cstream = Cc[
+      "@mozilla.org/intl/converter-input-stream;1"
+    ].createInstance(Ci.nsIConverterInputStream);
     try {
       fstream.init(aIdentity.signature, -1, 0, 0);
       try {
         cstream.init(fstream, charset, 1024, replacementChar);
-      }
-      catch (e) {
-        EnigmailLog.ERROR("ConverterInputStream init error: " + e +
-          "\n charset: " + charset + "\n");
+      } catch (e) {
+        EnigmailLog.ERROR(
+          "ConverterInputStream init error: " +
+            e +
+            "\n charset: " +
+            charset +
+            "\n"
+        );
         cstream.init(fstream, "UTF-8", 1024, replacementChar);
       }
       let str = {};
       while (cstream.readString(4096, str) != 0) {
         signature += str.value;
       }
       if (aIdentity.signature.path.match(/\.html?$/)) {
         signature = htmlToPlainText(signature);
       }
-    }
-    catch (e) {
+    } catch (e) {
       EnigmailLog.ERROR("Signature file stream error: " + e + "\n");
     }
     cstream.close();
     fstream.close();
     // required for stripSignatureIfNeeded working properly
     signature = signature.replace(/\r?\n/g, "\n");
-  }
-  else {
-    signature = aIdentity.htmlSigFormat ? htmlToPlainText(aIdentity.htmlSigText) : aIdentity.htmlSigText;
+  } else {
+    signature = aIdentity.htmlSigFormat
+      ? htmlToPlainText(aIdentity.htmlSigText)
+      : aIdentity.htmlSigText;
   }
   return signature;
 }
--- a/mail/extensions/openpgp/content/modules/stdlib/misc.jsm
+++ b/mail/extensions/openpgp/content/modules/stdlib/misc.jsm
@@ -5,63 +5,84 @@
 /**
  * @fileoverview This file provides various utilities: some helpers to deal with
  * identity management, some helpers for JS programming, some helpers for
  * low-level XPCOM stuff...
  */
 
 var EXPORTED_SYMBOLS = [
   // Identity management helpers
-  'gIdentities', 'fillIdentities', 'getIdentities', 'getDefaultIdentity', 'getIdentityForEmail',
+  "gIdentities",
+  "fillIdentities",
+  "getIdentities",
+  "getDefaultIdentity",
+  "getIdentityForEmail",
   // Account management helpers:
-  'hasConfiguredAccounts',
+  "hasConfiguredAccounts",
   // JS programming helpers
-  'range', 'MixIn', 'combine', 'entries',
+  "range",
+  "MixIn",
+  "combine",
+  "entries",
   // XPCOM helpers
-  'NS_FAILED', 'NS_SUCCEEDED',
+  "NS_FAILED",
+  "NS_SUCCEEDED",
   // Various formatting helpers
-  'dateAsInMessageList', 'escapeHtml', 'sanitize', 'parseMimeLine',
+  "dateAsInMessageList",
+  "escapeHtml",
+  "sanitize",
+  "parseMimeLine",
   // Useful for web content
-  'encodeUrlParameters', 'decodeUrlParameters',
+  "encodeUrlParameters",
+  "decodeUrlParameters",
   // Character set helpers
-  'systemCharset',
+  "systemCharset",
   // Platform-specific idioms
-  'isOSX', 'isWindows', 'isAccel'
-]
+  "isOSX",
+  "isWindows",
+  "isAccel",
+];
 
-const fixIterator = ChromeUtils.import("resource:///modules/iteratorUtils.jsm").fixIterator;
-const XPCOMUtils = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm").XPCOMUtils;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
+const fixIterator = ChromeUtils.import("resource:///modules/iteratorUtils.jsm")
+  .fixIterator;
+const XPCOMUtils = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm")
+  .XPCOMUtils;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
 var MailServices;
 try {
-  MailServices = ChromeUtils.import("resource:///modules/MailServices.jsm").MailServices;
-}
-catch (x){
-  MailServices = ChromeUtils.import("resource:///modules/mailServices.js").MailServices;
+  MailServices = ChromeUtils.import("resource:///modules/MailServices.jsm")
+    .MailServices;
+} catch (x) {
+  MailServices = ChromeUtils.import("resource:///modules/mailServices.js")
+    .MailServices;
 }
 
-XPCOMUtils.defineLazyServiceGetter(MailServices, "i18nDateFormatter",
-  "@mozilla.org/intl/scriptabledateformat;1");
+XPCOMUtils.defineLazyServiceGetter(
+  MailServices,
+  "i18nDateFormatter",
+  "@mozilla.org/intl/scriptabledateformat;1"
+);
 
-
-let isOSX = ("nsILocalFileMac" in Ci);
-let isWindows = ("@mozilla.org/windows-registry-key;1" in Cc);
+let isOSX = "nsILocalFileMac" in Ci;
+let isWindows = "@mozilla.org/windows-registry-key;1" in Cc;
 
 function isAccel(event) {
-  return isOSX && event.metaKey || event.ctrlKey;
+  return (isOSX && event.metaKey) || event.ctrlKey;
 }
 
 /**
  * Low-level XPCOM-style macro. You might need this for the composition and
  *  sending listeners which will pass you some status codes.
  * @param {Int} v The status code
  * @return {Bool}
  */
 function NS_FAILED(v) {
-  return (v & 0x80000000);
+  return v & 0x80000000;
 }
 
 /**
  * Low-level XPCOM-style macro. You might need this for the composition and
  *  sending listeners which will pass you some status codes.
  * @param {Int} v The status code
  * @return {Bool}
  */
@@ -96,20 +117,21 @@ function* entries(anObject) {
  * MixIn-style helper. Adds aMixIn properties, getters and setters to
  *  aConstructor.
  * @param {Object} aConstructor
  * @param {Object} aMixIn
  */
 function MixIn(aConstructor, aMixIn) {
   let proto = aConstructor.prototype;
   for (let [name, func] of entries(aMixIn)) {
-    if (name.substring(0, 4) == "get_")
+    if (name.substring(0, 4) == "get_") {
       proto.__defineGetter__(name.substring(4), func);
-    else
+    } else {
       proto[name] = func;
+    }
   }
 }
 
 /**
  * A global pointer to all the identities known for the user. Feel free to call
  *  fillIdentities again if you feel that the user has updated them!
  * The keys are email addresses, the values are <tt>nsIMsgIdentity</tt> objects.
  *
@@ -124,28 +146,32 @@ let gIdentities = {};
  * There is a "default" key, that we guarantee to be non-null, by picking the
  *  first account's first valid identity if the default account doesn't have any
  *  valid identity associated.
  * @param aSkipNntp (optional) Should we avoid including nntp identities in the
  *  list?
  * @deprecated Use getIdenties() instead
  */
 function fillIdentities(aSkipNntp) {
-  EnigmailLog.WARNING("fillIdentities is deprecated! Use getIdentities instead!\n");
-  EnigmailLog.DEBUG("Filling identities with skipnntp = " + aSkipNntp.toString() + "\n");
+  EnigmailLog.WARNING(
+    "fillIdentities is deprecated! Use getIdentities instead!\n"
+  );
+  EnigmailLog.DEBUG(
+    "Filling identities with skipnntp = " + aSkipNntp.toString() + "\n"
+  );
 
   for (let currentIdentity of getIdentities(aSkipNntp)) {
     gIdentities[currentIdentity.identity.email] = currentIdentity.identity;
     if (currentIdentity.isDefault) {
-      gIdentities["default"] = currentIdentity.identity;
+      gIdentities.default = currentIdentity.identity;
     }
   }
 
   if (!("default" in gIdentities)) {
-    gIdentities["default"] = getIdentities()[0].identity;
+    gIdentities.default = getIdentities()[0].identity;
   }
 }
 
 /**
  * Returns the default identity in the form { boolean isDefault; nsIMsgIdentity identity }
  */
 function getDefaultIdentity() {
   return getIdentities().find(x => x.isDefault);
@@ -154,50 +180,63 @@ function getDefaultIdentity() {
 /**
  * Returns a list of all identities in the form [{ boolean isDefault; nsIMsgIdentity identity }].
  * It is assured that there is exactly one default identity.
  * If only the default identity is needed, getDefaultIdentity() can be used.
  * @param aSkipNntpIdentities (default: true) Should we avoid including nntp identities in the list?
  */
 function getIdentities(aSkipNntpIdentities = true) {
   let identities = [];
-  for (let account of fixIterator(MailServices.accounts.accounts, Ci.nsIMsgAccount)) {
+  for (let account of fixIterator(
+    MailServices.accounts.accounts,
+    Ci.nsIMsgAccount
+  )) {
     let server = account.incomingServer;
-    if (aSkipNntpIdentities && (!server || server.type != "pop3" && server.type != "imap")) {
+    if (
+      aSkipNntpIdentities &&
+      (!server || (server.type != "pop3" && server.type != "imap"))
+    ) {
       continue;
     }
-    for (let currentIdentity of fixIterator(account.identities, Ci.nsIMsgIdentity)) {
+    for (let currentIdentity of fixIterator(
+      account.identities,
+      Ci.nsIMsgIdentity
+    )) {
       // We're only interested in identities that have a real email.
       if (currentIdentity.email) {
         identities.push({
-          isDefault: (currentIdentity == MailServices.accounts.defaultAccount ? MailServices.accounts.defaultAccount.defaultIdentity : false),
-          identity: currentIdentity
+          isDefault:
+            currentIdentity == MailServices.accounts.defaultAccount
+              ? MailServices.accounts.defaultAccount.defaultIdentity
+              : false,
+          identity: currentIdentity,
         });
       }
     }
   }
   if (identities.length == 0) {
     EnigmailLog.DEBUG("Didn't find any identities!\n");
-  }
-  else {
-    if (!identities.some(x => x.isDefault)) {
-      EnigmailLog.DEBUG("Didn't find any default key - mark the first identity as default!\n");
-      identities[0].isDefault = true;
-    }
+  } else if (!identities.some(x => x.isDefault)) {
+    EnigmailLog.DEBUG(
+      "Didn't find any default key - mark the first identity as default!\n"
+    );
+    identities[0].isDefault = true;
   }
   return identities;
 }
 
 /*
  * Searches a given email address in all identities and returns the corresponding identity.
  * @param {String} anEmailAddress Email address to be searched in the identities
  * @returns {{Boolean} isDefault, {{nsIMsgIdentity} identity} if found, otherwise undefined
  */
 function getIdentityForEmail(anEmailAddress) {
-  return getIdentities(false).find(ident => ident.identity.email.toLowerCase() == anEmailAddress.toLowerCase());
+  return getIdentities(false).find(
+    ident => ident.identity.email.toLowerCase() == anEmailAddress.toLowerCase()
+  );
 }
 
 /**
  * A stupid formatting function that uses the i18nDateFormatter XPCOM component
  * to format a date just like in the message list
  * @param {Date} aDate a javascript Date object
  * @return {String} a string containing the formatted date
  */
@@ -208,36 +247,34 @@ function dateAsInMessageList(aDate) {
   // Is it today?
   let isToday =
     now.getFullYear() == aDate.getFullYear() &&
     now.getMonth() == aDate.getMonth() &&
     now.getDate() == aDate.getDate();
 
   let options = {
     hour: DATE_2DIGIT,
-    minute: DATE_2DIGIT
+    minute: DATE_2DIGIT,
   };
 
   if (!isToday) {
     options.day = DATE_2DIGIT;
     options.month = DATE_2DIGIT;
     let year = aDate.getFullYear();
     if (year > 2099) {
       options.year = DATE_4DIGIT;
-    }
-    else {
+    } else {
       options.year = DATE_2DIGIT;
     }
   }
 
   return new Intl.DateTimeFormat([], options).format(aDate);
 }
 
-
-const RE_SANITIZE = /[\u0000-\u0008\u000b-\u000c\u000e-\u001f]/g;
+const RE_SANITIZE = /[\u0000-\u0008\u000b-\u000c\u000e-\u001f]/g; // eslint-disable-line no-control-regex
 
 /**
  * Helper function to remove non-printable characters from a string -- injecting
  * these in an XML or XHTML document would cause an error.
  * @param {String} s input text
  * @param {String} The sanitized string.
  */
 function sanitize(s) {
@@ -248,28 +285,30 @@ function sanitize(s) {
  * Helper function to escape some XML chars, so they display properly in
  *  innerHTML.
  * @param {String} s input text
  * @return {String} The string with &lt;, &gt;, and &amp; replaced by the corresponding entities.
  */
 function escapeHtml(s) {
   s += "";
   // stolen from selectionsummaries.js (thanks davida!)
-  return sanitize(s.replace(/[<>&]/g, function(s) {
-    switch (s) {
-      case "<":
-        return "&lt;";
-      case ">":
-        return "&gt;";
-      case "&":
-        return "&amp;";
-      default:
-        throw Error("Unexpected match");
-    }
-  }));
+  return sanitize(
+    s.replace(/[<>&]/g, function(s) {
+      switch (s) {
+        case "<":
+          return "&lt;";
+        case ">":
+          return "&gt;";
+        case "&":
+          return "&amp;";
+        default:
+          throw Error("Unexpected match");
+      }
+    })
+  );
 }
 
 /**
  * Wraps the low-level header parser stuff.
  * @param {String} aMimeLine a line that looks like "John &lt;john@cheese.com&gt;, Jane &lt;jane@wine.com&gt;"
  * @param {Boolean} aDontFix (optional) Default to false. Shall we return an
  *  empty array in case aMimeLine is empty?
  * @return {Array} a list of { email, name } objects
@@ -277,36 +316,40 @@ function escapeHtml(s) {
 function parseMimeLine(aMimeLine, aDontFix) {
   if (aMimeLine == null) {
     EnigmailLog.DEBUG("Empty aMimeLine?!!\n");
     return [];
   }
   let emails = {};
   let fullNames = {};
   let names = {};
-  let numAddresses = MailServices.headerParser.parseHeadersWithArray(aMimeLine,
+  let numAddresses = MailServices.headerParser.parseHeadersWithArray(
+    aMimeLine,
     emails,
     names,
-    fullNames);
-  if (numAddresses)
+    fullNames
+  );
+  if (numAddresses) {
     return [...range(0, numAddresses)].map(i => {
       return {
         email: emails.value[i],
         name: names.value[i],
-        fullName: fullNames.value[i]
+        fullName: fullNames.value[i],
       };
     });
-  else if (aDontFix)
+  } else if (aDontFix) {
     return [];
-  else
-    return [{
+  }
+  return [
+    {
       email: "",
       name: "-",
-      fullName: "-"
-    }];
+      fullName: "-",
+    },
+  ];
 }
 
 /**
  * Takes an object whose keys are the parameter names, whose values are strings
  * that are to be encoded in the url.
  * @param aObj
  * @return param1=val1&param2=val2 etc.
  */
@@ -342,54 +385,61 @@ function decodeUrlParameters(aStr) {
 /**
  * Returns a system character set string, which is system code page on Windows,
  * LANG environment variable's encoding on Unix-like OS, otherwise UTF-8.
  * @return {String} a character set string
  */
 function systemCharset() {
   let charset = "UTF-8";
   if ("@mozilla.org/windows-registry-key;1" in Cc) {
-    let registry = Cc["@mozilla.org/windows-registry-key;1"]
-      .createInstance(Ci.nsIWindowsRegKey);
-    registry.open(registry.ROOT_KEY_LOCAL_MACHINE,
+    let registry = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
+      Ci.nsIWindowsRegKey
+    );
+    registry.open(
+      registry.ROOT_KEY_LOCAL_MACHINE,
       "SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage",
-      registry.ACCESS_READ);
+      registry.ACCESS_READ
+    );
     let codePage = registry.readStringValue("ACP");
     if (codePage) {
       charset = "CP" + codePage;
     }
     registry.close();
-  }
-  else {
-    let env = Cc["@mozilla.org/process/environment;1"]
-      .getService(Ci.nsIEnvironment);
+  } else {
+    let env = Cc["@mozilla.org/process/environment;1"].getService(
+      Ci.nsIEnvironment
+    );
     let lang = env.get("LANG").split(".");
     if (lang.length > 1) {
       charset = lang[1];
     }
   }
   return charset;
 }
 
 function combine(a1, a2) {
-  if (a1.length != a2.length)
+  if (a1.length != a2.length) {
     throw new Error("combine: the given arrays have different lengths");
+  }
   return [...range(0, a1.length)].map(i => [a1[i], a2[i]]);
 }
 
-
 /**
  * Determine if at least one account / identity is configured
  * @return {Bool}
  */
 function hasConfiguredAccounts() {
-  let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+  let accountManager = Cc[
+    "@mozilla.org/messenger/account-manager;1"
+  ].getService(Ci.nsIMsgAccountManager);
 
   for (let acct = 0; acct < accountManager.accounts.length; acct++) {
     let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);
 
     if (ac.incomingServer.type !== "none") {
-      if (ac.defaultIdentity.email.length > 0) return true;
+      if (ac.defaultIdentity.email.length > 0) {
+        return true;
+      }
     }
   }
 
   return false;
 }
--- a/mail/extensions/openpgp/content/modules/stdlib/msgHdrUtils.jsm
+++ b/mail/extensions/openpgp/content/modules/stdlib/msgHdrUtils.jsm
@@ -6,86 +6,77 @@
  * @fileoverview A whole bunch of utility functions that will abstract away
  *  various low-level nsIMsgDbHdr operations. The idea is to save time by not
  *  having to lookup how to do simple actions.
  * @author Jonathan Protzenko
  */
 
 var EXPORTED_SYMBOLS = [
   // Low-level XPCOM boring stuff
-  'msgHdrToMessageBody', 'msgHdrToNeckoURL', 'msgHdrGetTags', 'msgUriToMsgHdr',
-  'msgHdrGetUri', 'msgHdrFromNeckoUrl', 'msgHdrSetTags',
+  "msgHdrToMessageBody",
+  "msgHdrToNeckoURL",
+  "msgHdrGetTags",
+  "msgUriToMsgHdr",
+  "msgHdrGetUri",
+  "msgHdrFromNeckoUrl",
+  "msgHdrSetTags",
   // Quickly identify a message
-  'msgHdrIsDraft', 'msgHdrIsSent', 'msgHdrIsArchive', 'msgHdrIsInbox',
-  'msgHdrIsRss', 'msgHdrIsNntp', 'msgHdrIsJunk',
+  "msgHdrIsDraft",
+  "msgHdrIsSent",
+  "msgHdrIsArchive",
+  "msgHdrIsInbox",
+  "msgHdrIsRss",
+  "msgHdrIsNntp",
+  "msgHdrIsJunk",
   // Actions on a set of message headers
-  'msgHdrsMarkAsRead', 'msgHdrsArchive', 'msgHdrsDelete',
+  "msgHdrsMarkAsRead",
+  "msgHdrsArchive",
+  "msgHdrsDelete",
   // Doesn't really belong here
-  'getMail3Pane',
+  "getMail3Pane",
   // Higher-level functions
-  'msgHdrGetHeaders',
+  "msgHdrGetHeaders",
   // Modify messages, raw.
-  'msgHdrsModifyRaw',
-]
-
-const Cr = Components.results;
+  "msgHdrsModifyRaw",
+];
 
 // from mailnews/base/public/nsMsgFolderFlags.idl
 const nsMsgFolderFlags_SentMail = 0x00000200;
 const nsMsgFolderFlags_Drafts = 0x00000400;
 const nsMsgFolderFlags_Archive = 0x00004000;
 const nsMsgFolderFlags_Inbox = 0x00001000;
 
 const PR_WRONLY = 0x02;
 
-const XPCOMUtils = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm").XPCOMUtils;
-const {
-  MsgHdrToMimeMessage,
-  MimeMessage, MimeContainer,
-  MimeBody, MimeUnknown,
-  MimeMessageAttachment
-} = ChromeUtils.import("resource:///modules/gloda/MimeMessage.jsm");
-const GlodaUtils = ChromeUtils.import("resource:///modules/gloda/GlodaUtils.jsm").GlodaUtils;
-const {
-  fixIterator, toXPCOMArray, toArray
-} =ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
-const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const XPCOMUtils = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm")
+  .XPCOMUtils;
+const { MsgHdrToMimeMessage, MimeMessage } = ChromeUtils.import(
+  "resource:///modules/gloda/MimeMessage.jsm"
+);
+const { toXPCOMArray } = ChromeUtils.import(
+  "resource:///modules/iteratorUtils.jsm"
+);
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
 
 var MailServices;
 try {
-  MailServices = ChromeUtils.import("resource:///modules/MailServices.jsm").MailServices;
-}
-catch (x){
-  MailServices = ChromeUtils.import("resource:///modules/mailServices.js").MailServices;
+  MailServices = ChromeUtils.import("resource:///modules/MailServices.jsm")
+    .MailServices;
+} catch (x) {
+  MailServices = ChromeUtils.import("resource:///modules/mailServices.js")
+    .MailServices;
 }
 
-const {
-  gIdentities,
-  fillIdentities,
-  getIdentities,
-  getDefaultIdentity,
-  getIdentityForEmail,
-  hasConfiguredAccounts,
-  range,
-  MixIn,
-  combine,
-  entries,
-  dateAsInMessageList,
-  escapeHtml,
-  sanitize,
-  parseMimeLine,
-  encodeUrlParameters,
-  decodeUrlParameters,
-  systemCharset,
-  isOSX,
-  isWindows,
-  isAccel
-} = ChromeUtils.import("chrome://openpgp/content/modules/stdlib/misc.jsm");
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
+const { entries, NS_SUCCEEDED } = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib/misc.jsm"
+);
 
 // Adding a messenger lazy getter to the MailServices even though it's not a service
 XPCOMUtils.defineLazyGetter(MailServices, "messenger", function() {
   return Cc["@mozilla.org/messenger;1"].createInstance(Ci.nsIMessenger);
 });
 
 /**
  * Get a given message header's uri.
@@ -100,18 +91,17 @@ function msgHdrGetUri(aMsg) {
  * Get a msgHdr from a message URI (msgHdr.URI).
  * @param {String} aUri The URI of the message
  * @return {nsIMsgDbHdr}
  */
 function msgUriToMsgHdr(aUri) {
   try {
     let messageService = MailServices.messenger.messageServiceFromURI(aUri);
     return messageService.messageURIToMsgHdr(aUri);
-  }
-  catch (e) {
+  } catch (e) {
     dump("Unable to get " + aUri + " — returning null instead");
     return null;
   }
 }
 
 /**
  * Tells if the message is in the account's inbox
  * @param {nsIMsgDbHdr} msgHdr The message header to examine
@@ -159,29 +149,42 @@ function msgHdrFromNeckoUrl(aUrl) {
 
 /**
  * Get a string containing the body of a messsage.
  * @param {nsIMsgDbHdr} aMessageHeader The message header
  * @param {bool} aStripHtml Keep html?
  * @return {string}
  */
 function msgHdrToMessageBody(aMessageHeader, aStripHtml, aLength) {
-  let messenger = Cc["@mozilla.org/messenger;1"].createInstance(Ci.nsIMessenger);
-  let listener = Cc["@mozilla.org/network/sync-stream-listener;1"].createInstance(Ci.nsISyncStreamListener);
+  let messenger = Cc["@mozilla.org/messenger;1"].createInstance(
+    Ci.nsIMessenger
+  );
+  let listener = Cc[
+    "@mozilla.org/network/sync-stream-listener;1"
+  ].createInstance(Ci.nsISyncStreamListener);
   let uri = aMessageHeader.folder.getUriForMsg(aMessageHeader);
-  messenger.messageServiceFromURI(uri).streamMessage(uri, listener, null, null, false, "");
+  messenger
+    .messageServiceFromURI(uri)
+    .streamMessage(uri, listener, null, null, false, "");
   let folder = aMessageHeader.folder;
   /*
    * AUTF8String getMsgTextFromStream(in nsIInputStream aStream, in ACString aCharset,
                                       in unsigned long aBytesToRead, in unsigned long aMaxOutputLen,
                                       in boolean aCompressQuotes, in boolean aStripHTMLTags,
                                       out ACString aContentType);
   */
   return folder.getMsgTextFromStream(
-    listener.inputStream, aMessageHeader.Charset, 2 * aLength, aLength, false, aStripHtml, {});
+    listener.inputStream,
+    aMessageHeader.Charset,
+    2 * aLength,
+    aLength,
+    false,
+    aStripHtml,
+    {}
+  );
 }
 
 /**
  * Get a nsIURI from a nsIMsgDBHdr
  * @param {nsIMsgDbHdr} aMsgHdr The message header
  * @return {nsIURI}
  */
 function msgHdrToNeckoURL(aMsgHdr) {
@@ -197,17 +200,17 @@ function msgHdrToNeckoURL(aMsgHdr) {
  * just does the messy work of understanding how tags are
  * stored in nsIMsgDBHdrs.
  *
  * @param {nsIMsgDbHdr} aMsgHdr the msgHdr whose tags we want
  * @return {nsIMsgTag array} a list of tag objects
  */
 function msgHdrGetTags(aMsgHdr) {
   let keywords = aMsgHdr.getStringProperty("keywords");
-  let keywordList = keywords.split(' ');
+  let keywordList = keywords.split(" ");
   let keywordMap = {};
   for (let keyword of keywordList) {
     keywordMap[keyword] = true;
   }
 
   let tagArray = MailServices.tags.getAllTags({});
   let tags = tagArray.filter(tag => tag.key in keywordMap);
   return tags;
@@ -217,23 +220,25 @@ function msgHdrGetTags(aMsgHdr) {
  * Set the tags for a given msgHdr.
  *
  * @param {nsIMsgDBHdr} aMsgHdr
  * @param {nsIMsgTag array} aTags
  */
 function msgHdrSetTags(aMsgHdr, aTags) {
   let oldTagList = msgHdrGetTags(aMsgHdr);
   let oldTags = {}; // hashmap
-  for (let tag of oldTagList)
+  for (let tag of oldTagList) {
     oldTags[tag.key] = null;
+  }
 
   let newTags = {};
   let newTagList = aTags;
-  for (let tag of newTagList)
+  for (let tag of newTagList) {
     newTags[tag.key] = null;
+  }
 
   let toAdd = newTagList.filter(x => !(x.key in oldTags)).map(x => x.key);
   let toRemove = oldTagList.filter(x => !(x.key in newTags)).map(x => x.key);
 
   let folder = aMsgHdr.folder;
   let msgHdr = toXPCOMArray([aMsgHdr], Ci.nsIMutableArray);
   folder.addKeywordsToMessages(msgHdr, toAdd.join(" "));
   folder.removeKeywordsFromMessages(msgHdr, toRemove.join(" "));
@@ -243,84 +248,90 @@ function msgHdrSetTags(aMsgHdr, aTags) {
 /**
  * Mark an array of msgHdrs read (or unread)
  * @param {nsIMsgDbHdr array} msgHdrs The message headers
  * @param {bool} read True to mark them read, false to mark them unread
  */
 function msgHdrsMarkAsRead(msgHdrs, read) {
   let pending = {};
   for (let msgHdr of msgHdrs) {
-    if (msgHdr.isRead == read)
+    if (msgHdr.isRead == read) {
       continue;
+    }
     if (!pending[msgHdr.folder.URI]) {
       pending[msgHdr.folder.URI] = {
         folder: msgHdr.folder,
-        msgs: Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray)
+        msgs: Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray),
       };
     }
-    pending[msgHdr.folder.URI].msgs.appendElement(msgHdr, false);
+    pending[msgHdr.folder.URI].msgs.appendElement(msgHdr);
   }
-  for (let [uri, {
-      folder, msgs
-    }] of entries(pending)) {
+  for (let [{ folder, msgs }] of entries(pending)) {
     folder.markMessagesRead(msgs, read);
     folder.msgDatabase = null; /* don't leak */
   }
 }
 
 /**
  * Delete a set of messages.
  * @param {nsIMsgDbHdr array} msgHdrs The message headers
  */
 function msgHdrsDelete(msgHdrs) {
   let pending = {};
   for (let msgHdr of msgHdrs) {
     if (!pending[msgHdr.folder.URI]) {
       pending[msgHdr.folder.URI] = {
         folder: msgHdr.folder,
-        msgs: Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray)
+        msgs: Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray),
       };
     }
-    pending[msgHdr.folder.URI].msgs.appendElement(msgHdr, false);
+    pending[msgHdr.folder.URI].msgs.appendElement(msgHdr);
   }
-  for (let [uri, {
-      folder, msgs
-    }] of entries(pending)) {
-    folder.deleteMessages(msgs, getMail3Pane().msgWindow, false, false, null, true);
+  for (let [{ folder, msgs }] of entries(pending)) {
+    folder.deleteMessages(
+      msgs,
+      getMail3Pane().msgWindow,
+      false,
+      false,
+      null,
+      true
+    );
     folder.msgDatabase = null; /* don't leak */
   }
 }
 
 /**
  * Get the main Thunderbird window. Used heavily to get a reference to globals
  *  that are defined in mail/base/content/.
  * @return The window object for the main window.
  */
 function getMail3Pane() {
-  return Cc["@mozilla.org/appshell/window-mediator;1"]
-    .getService(Ci.nsIWindowMediator)
-    .getMostRecentWindow("mail:3pane");
+  return Services.wm.getMostRecentWindow("mail:3pane");
 }
 
 /**
  * Archive a set of messages
  * @param {nsIMsgDbHdr array} msgHdrs The message headers
  */
 function msgHdrsArchive(msgHdrs) {
   /* See
    * http://mxr.mozilla.org/comm-central/source/suite/mailnews/mailWindowOverlay.js#1337
    *
    * The window is here because otherwise we don't have access to
    * BatchMessageMover.
    * */
   let mail3PaneWindow = getMail3Pane();
   let batchMover = new mail3PaneWindow.BatchMessageMover();
-  batchMover.archiveMessages(msgHdrs.filter(
-    x => !msgHdrIsArchive(x) && getMail3Pane().getIdentityForHeader(x).archiveEnabled
-  ));
+  batchMover.archiveMessages(
+    msgHdrs.filter(
+      x =>
+        !msgHdrIsArchive(x) &&
+        getMail3Pane().getIdentityForHeader(x).archiveEnabled
+    )
+  );
 }
 
 /**
  * Tell if a message is an RSS feed iteme
  * @param {nsIMsgDbHdr} msgHdr The message header
  * @return {Bool}
  */
 function msgHdrIsRss(msgHdr) {
@@ -337,17 +348,19 @@ function msgHdrIsNntp(msgHdr) {
 }
 
 /**
  * Tell if a message has been marked as junk.
  * @param {nsIMsgDbHdr} msgHdr The message header
  * @return {Bool}
  */
 function msgHdrIsJunk(aMsgHdr) {
-  return aMsgHdr.getStringProperty("junkscore") == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE;
+  return (
+    aMsgHdr.getStringProperty("junkscore") == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE
+  );
 }
 
 /**
  * Recycling the HeaderHandlerBase from MimeMessage.jsm
  */
 function HeaderHandler(aHeaders) {
   this.headers = aHeaders;
 }
@@ -360,87 +373,102 @@ HeaderHandler.prototype = {
  * Creates a stream listener that will call k once done, passing it the string
  * that has been read.
  */
 function createStreamListener(k) {
   return {
     _data: "",
     _stream: null,
 
-    QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener, Ci.nsIRequestObserver]),
+    QueryInterface: ChromeUtils.generateQI([
+      Ci.nsIStreamListener,
+      Ci.nsIRequestObserver,
+    ]),
 
     // nsIRequestObserver
-    onStartRequest: function(aRequest) {},
-    onStopRequest: function(aRequest, aStatusCode) {
+    onStartRequest(aRequest) {},
+    onStopRequest(aRequest, aStatusCode) {
       try {
         k(this._data);
-      }
-      catch (e) {
+      } catch (e) {
         dump("Error inside stream listener:\n" + e + "\n");
       }
     },
 
     // nsIStreamListener
-    onDataAvailable: function(aRequest, dummy, aInputStream, aOffset, aCount) {
+    onDataAvailable(aRequest, dummy, aInputStream, aOffset, aCount) {
       aInputStream = dummy;
       aCount = aOffset;
       if (this._stream == null) {
-        this._stream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
+        this._stream = Cc[
+          "@mozilla.org/scriptableinputstream;1"
+        ].createInstance(Ci.nsIScriptableInputStream);
         this._stream.init(aInputStream);
       }
       this._data += this._stream.read(aCount);
-    }
+    },
   };
 }
 
 /**
  * @param aMsgHdr The message header whose headers you want
  * @param k A function that takes a HeaderHandler object (see MimeMessage.jsm).
  *  Such an object has a get function, a has function. It has a header property,
  *  whose keys are lowercased header names, and whose values are list of
  *  strings corresponding to the multiple entries found for that header.
  */
 function msgHdrGetHeaders(aMsgHdr, k) {
   let uri = msgHdrGetUri(aMsgHdr);
   let messageService = MailServices.messenger.messageServiceFromURI(uri);
 
   let fallback = () =>
-    MsgHdrToMimeMessage(aMsgHdr, null, function(aMsgHdr, aMimeMsg) {
-      k(aMimeMsg);
-    }, true, {
-      partsOnDemand: true,
-    });
+    MsgHdrToMimeMessage(
+      aMsgHdr,
+      null,
+      function(aMsgHdr, aMimeMsg) {
+        k(aMimeMsg);
+      },
+      true,
+      {
+        partsOnDemand: true,
+      }
+    );
 
   // This is intentionally disabled because there's a bug in Thunderbird that
   // renders the supposedly-useful streamHeaders function unusable.
   if (false && "streamHeaders" in messageService) {
     try {
-      messageService.streamHeaders(uri, createStreamListener(aRawString => {
-        let re = /\r?\n\s+/g;
-        let str = aRawString.replace(re, " ");
-        let lines = str.split(/\r?\n/);
-        let obj = {};
-        for (let line of lines) {
-          let i = line.indexOf(":");
-          if (i < 0)
-            continue;
-          let k = line.substring(0, i).toLowerCase();
-          let v = line.substring(i + 1).trim();
-          if (!(k in obj))
-            obj[k] = [];
-          obj[k].push(v);
-        }
-        k(new HeaderHandler(obj));
-      }), null, true);
-    }
-    catch (e) {
+      messageService.streamHeaders(
+        uri,
+        createStreamListener(aRawString => {
+          let re = /\r?\n\s+/g;
+          let str = aRawString.replace(re, " ");
+          let lines = str.split(/\r?\n/);
+          let obj = {};
+          for (let line of lines) {
+            let i = line.indexOf(":");
+            if (i < 0) {
+              continue;
+            }
+            let k = line.substring(0, i).toLowerCase();
+            let v = line.substring(i + 1).trim();
+            if (!(k in obj)) {
+              obj[k] = [];
+            }
+            obj[k].push(v);
+          }
+          k(new HeaderHandler(obj));
+        }),
+        null,
+        true
+      );
+    } catch (e) {
       fallback();
     }
-  }
-  else {
+  } else {
     fallback();
   }
 }
 
 /**
  * @param aMsgHdrs The messages to modify
  * @param aTransformer A function which takes the input data, modifies it, and
  * returns the corresponding data. This is the _raw_ contents of the message.
@@ -451,72 +479,80 @@ function msgHdrsModifyRaw(aMsgHdrs, aTra
   let copyNext = () => {
     dump("msgHdrModifyRaw: copying next\n");
     let obj = toCopy.pop();
     if (!obj) {
       msgHdrsDelete(toDelete);
       return;
     }
 
-    let {
-      msgHdr, tempFile
-    } = obj;
+    let { msgHdr, tempFile } = obj;
 
     EnigmailCompat.copyFileToMailFolder(
       tempFile,
       msgHdr.folder,
       msgHdr.flags,
-      msgHdr.getStringProperty("keywords"), {
-        QueryInterface: XPCOMUtils.generateQI([Ci.nsIMsgCopyServiceListener]),
+      msgHdr.getStringProperty("keywords"),
+      {
+        QueryInterface: ChromeUtils.generateQI([Ci.nsIMsgCopyServiceListener]),
 
-        OnStartCopy: function() {},
-        OnProgress: function(aProgress, aProgressMax) {},
-        SetMessageKey: function(aKey) {},
-        GetMessageId: function(aMessageId) {},
-        OnStopCopy: function(aStatus) {
+        OnStartCopy() {},
+        OnProgress(aProgress, aProgressMax) {},
+        SetMessageKey(aKey) {},
+        GetMessageId(aMessageId) {},
+        OnStopCopy(aStatus) {
           if (NS_SUCCEEDED(aStatus)) {
             dump("msgHdrModifyRaw: copied successfully\n");
             toDelete.push(msgHdr);
             tempFile.remove(false);
           }
           copyNext();
-        }
+        },
       },
       null
     );
   };
 
   let count = aMsgHdrs.length;
   let tick = function() {
-    if (--count == 0)
+    if (--count == 0) {
       copyNext();
-  }
+    }
+  };
 
   for (let aMsgHdr of aMsgHdrs) {
     let msgHdr = aMsgHdr;
     let uri = msgHdrGetUri(msgHdr);
     let messageService = MailServices.messenger.messageServiceFromURI(uri);
-    messageService.streamMessage(uri, createStreamListener(function(aRawString) {
-      let data = aTransformer(aRawString);
-      if (!data) {
-        dump("msgHdrModifyRaw: no data, aborting\n");
-        return;
-      }
+    messageService.streamMessage(
+      uri,
+      createStreamListener(function(aRawString) {
+        let data = aTransformer(aRawString);
+        if (!data) {
+          dump("msgHdrModifyRaw: no data, aborting\n");
+          return;
+        }
 
-      let tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile);
-      tempFile.append("rethread.eml");
-      tempFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0600", 8));
+        let tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile);
+        tempFile.append("rethread.eml");
+        tempFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0600", 8));
 
-      let stream = Cc["@mozilla.org/network/file-output-stream;1"]
-        .createInstance(Ci.nsIFileOutputStream);
-      stream.init(tempFile, PR_WRONLY, parseInt("0600", 8), 0);
-      stream.write(data, data.length);
-      stream.close();
+        let stream = Cc[
+          "@mozilla.org/network/file-output-stream;1"
+        ].createInstance(Ci.nsIFileOutputStream);
+        stream.init(tempFile, PR_WRONLY, parseInt("0600", 8), 0);
+        stream.write(data, data.length);
+        stream.close();
 
-      dump("msgHdrModifyRaw: wrote to file\n");
-      toCopy.push({
-        tempFile: tempFile,
-        msgHdr: msgHdr
-      });
-      tick();
-    }), null, null, false, "");
+        dump("msgHdrModifyRaw: wrote to file\n");
+        toCopy.push({
+          tempFile,
+          msgHdr,
+        });
+        tick();
+      }),
+      null,
+      null,
+      false,
+      ""
+    );
   }
 }
--- a/mail/extensions/openpgp/content/modules/streams.jsm
+++ b/mail/extensions/openpgp/content/modules/streams.jsm
@@ -3,76 +3,88 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailStreams"];
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
-const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm").NetUtil;
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm")
+  .NetUtil;
 
-const NS_STRING_INPUT_STREAM_CONTRACTID = "@mozilla.org/io/string-input-stream;1";
-const NS_INPUT_STREAM_CHNL_CONTRACTID = "@mozilla.org/network/input-stream-channel;1";
-const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
+const NS_STRING_INPUT_STREAM_CONTRACTID =
+  "@mozilla.org/io/string-input-stream;1";
+const NS_INPUT_STREAM_CHNL_CONTRACTID =
+  "@mozilla.org/network/input-stream-channel;1";
 
 var EnigmailStreams = {
-
   /**
    * Create a new channel from a URL or URI.
    *
    * @param url: String, nsIURI or nsIFile -  URL specification
    *
    * @return: channel
    */
-  createChannel: function(url) {
+  createChannel(url) {
     let c = NetUtil.newChannel({
       uri: url,
-      loadUsingSystemPrincipal: true
+      loadUsingSystemPrincipal: true,
     });
 
     return c;
   },
 
-
   /**
    * create an nsIStreamListener object to read String data from an nsIInputStream
    *
    * @onStopCallback: Function - function(data) that is called when the stream has stopped
    *                             string data is passed as |data|
    *
    * @return: the nsIStreamListener to pass to the stream
    */
-  newStringStreamListener: function(onStopCallback) {
+  newStringStreamListener(onStopCallback) {
     EnigmailLog.DEBUG("enigmailCommon.jsm: newStreamListener\n");
 
     let listener = {
       data: "",
-      inStream: Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream),
+      inStream: Cc["@mozilla.org/binaryinputstream;1"].createInstance(
+        Ci.nsIBinaryInputStream
+      ),
       _onStopCallback: onStopCallback,
-      QueryInterface: EnigmailCompat.generateQI([Ci.nsIStreamListener, Ci.nsIRequestObserver]),
+      QueryInterface: EnigmailCompat.generateQI([
+        Ci.nsIStreamListener,
+        Ci.nsIRequestObserver,
+      ]),
 
-      onStartRequest: function(channel) {
+      onStartRequest(channel) {
         // EnigmailLog.DEBUG("enigmailCommon.jsm: stringListener.onStartRequest\n");
       },
 
-      onStopRequest: function(channel, status) {
+      onStopRequest(channel, status) {
         // EnigmailLog.DEBUG("enigmailCommon.jsm: stringListener.onStopRequest: "+ctxt+"\n");
         this.inStream = null;
         var cbFunc = this._onStopCallback;
         var cbData = this.data;
 
-        EnigmailTimer.setTimeout(function _cb() {
+        EnigmailTimer.setTimeout(function() {
           cbFunc(cbData);
         });
-      }
+      },
     };
 
     listener.onDataAvailable = function(req, stream, offset, count) {
       // EnigmailLog.DEBUG("enigmailCommon.jsm: stringListener.onDataAvailable: "+count+"\n");
       this.inStream.setInputStream(stream);
       this.data += this.inStream.readBytes(count);
     };
 
@@ -85,77 +97,92 @@ var EnigmailStreams = {
    * @uri:            nsIURI - object representing the URI that will deliver the data
    * @contentType:    String - the content type as specified in nsIChannel
    * @contentCharset: String - the character set; automatically determined if null
    * @data:           String - the data to feed to the stream
    * @loadInfo        nsILoadInfo - loadInfo (optional)
    *
    * @return nsIChannel object
    */
-  newStringChannel: function(uri, contentType, contentCharset, data, loadInfo) {
+  newStringChannel(uri, contentType, contentCharset, data, loadInfo) {
     EnigmailLog.DEBUG("enigmailCommon.jsm: newStringChannel\n");
 
     if (!loadInfo) {
       loadInfo = createLoadInfo();
     }
 
-    const inputStream = Cc[NS_STRING_INPUT_STREAM_CONTRACTID].createInstance(Ci.nsIStringInputStream);
+    const inputStream = Cc[NS_STRING_INPUT_STREAM_CONTRACTID].createInstance(
+      Ci.nsIStringInputStream
+    );
     inputStream.setData(data, -1);
 
     if (!contentCharset || contentCharset.length === 0) {
-      const ioServ = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
+      const ioServ = Services.io;
       const netUtil = ioServ.QueryInterface(Ci.nsINetUtil);
       const newCharset = {};
       const hadCharset = {};
-      let mimeType;
-      mimeType = netUtil.parseResponseContentType(contentType, newCharset, hadCharset);
+      netUtil.parseResponseContentType(contentType, newCharset, hadCharset);
       contentCharset = newCharset.value;
     }
 
-    let isc = Cc[NS_INPUT_STREAM_CHNL_CONTRACTID].createInstance(Ci.nsIInputStreamChannel);
+    let isc = Cc[NS_INPUT_STREAM_CHNL_CONTRACTID].createInstance(
+      Ci.nsIInputStreamChannel
+    );
     isc.QueryInterface(Ci.nsIChannel);
     isc.setURI(uri);
     isc.loadInfo = loadInfo;
     isc.contentStream = inputStream;
 
-    if (contentType && contentType.length) isc.contentType = contentType;
-    if (contentCharset && contentCharset.length) isc.contentCharset = contentCharset;
+    if (contentType && contentType.length) {
+      isc.contentType = contentType;
+    }
+    if (contentCharset && contentCharset.length) {
+      isc.contentCharset = contentCharset;
+    }
 
     EnigmailLog.DEBUG("enigmailCommon.jsm: newStringChannel - done\n");
 
     return isc;
   },
 
-  newFileChannel: function(uri, file, contentType, deleteOnClose) {
-    EnigmailLog.DEBUG("enigmailCommon.jsm: newFileChannel for '" + file.path + "'\n");
+  newFileChannel(uri, file, contentType, deleteOnClose) {
+    EnigmailLog.DEBUG(
+      "enigmailCommon.jsm: newFileChannel for '" + file.path + "'\n"
+    );
 
-    let inputStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
+    let inputStream = Cc[
+      "@mozilla.org/network/file-input-stream;1"
+    ].createInstance(Ci.nsIFileInputStream);
     let behaviorFlags = Ci.nsIFileInputStream.CLOSE_ON_EOF;
     if (deleteOnClose) {
       behaviorFlags |= Ci.nsIFileInputStream.DELETE_ON_CLOSE;
     }
     const ioFlags = 0x01; // readonly
     const perm = 0;
     inputStream.init(file, ioFlags, perm, behaviorFlags);
 
-    let isc = Cc[NS_INPUT_STREAM_CHNL_CONTRACTID].createInstance(Ci.nsIInputStreamChannel);
+    let isc = Cc[NS_INPUT_STREAM_CHNL_CONTRACTID].createInstance(
+      Ci.nsIInputStreamChannel
+    );
     isc.QueryInterface(Ci.nsIChannel);
     isc.contentDisposition = Ci.nsIChannel.DISPOSITION_ATTACHMENT;
     isc.loadInfo = createLoadInfo();
     isc.setURI(uri);
     isc.contentStream = inputStream;
 
-    if (contentType && contentType.length) isc.contentType = contentType;
+    if (contentType && contentType.length) {
+      isc.contentType = contentType;
+    }
 
     EnigmailLog.DEBUG("enigmailCommon.jsm: newStringChannel - done\n");
 
     return isc;
-  }
+  },
 };
 
 function createLoadInfo() {
   let c = NetUtil.newChannel({
     uri: "chrome://openpgp/content/",
-    loadUsingSystemPrincipal: true
+    loadUsingSystemPrincipal: true,
   });
 
   return c.loadInfo;
 }
--- a/mail/extensions/openpgp/content/modules/time.jsm
+++ b/mail/extensions/openpgp/content/modules/time.jsm
@@ -3,60 +3,60 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailTime"];
 
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
 
 const DATE_2DIGIT = "2-digit";
 const DATE_4DIGIT = "numeric";
 
 var EnigmailTime = {
   /**
    * Transform a Unix-Timestamp to a human-readable date/time string
    *
    * @dateNum:  Number  - Unix timestamp
    * @withDate: Boolean - if true, include the date in the output
    * @withTime: Boolean - if true, include the time in the output
    *
    * @return: String - formatted date/time string
    */
-  getDateTime: function(dateNum, withDate, withTime) {
+  getDateTime(dateNum, withDate, withTime) {
     if (dateNum && dateNum !== 0) {
       let dat = new Date(dateNum * 1000);
       let appLocale = EnigmailLocale.get();
 
       var options = {};
 
       if (withDate) {
         options.day = DATE_2DIGIT;
         options.month = DATE_2DIGIT;
         let year = dat.getFullYear();
         if (year > 2099) {
           options.year = DATE_4DIGIT;
-        }
-        else {
+        } else {
           options.year = DATE_2DIGIT;
         }
       }
       if (withTime) {
         options.hour = DATE_2DIGIT;
         options.minute = DATE_2DIGIT;
       }
 
       let useLocale = appLocale.getCategory("NSILOCALE_TIME").substr(0, 5);
       useLocale = useLocale.replace(/_/g, "-");
 
       try {
         return new Intl.DateTimeFormat(useLocale, options).format(dat);
       } catch (ex) {
         return new Intl.DateTimeFormat("en-US", options).format(dat);
       }
-    }
-    else {
+    } else {
       return "";
     }
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/timer.jsm
+++ b/mail/extensions/openpgp/content/modules/timer.jsm
@@ -3,34 +3,32 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailTimer"];
 
-const {
-  setTimeout,
-  clearTimeout
-} = ChromeUtils.import("resource://gre/modules/Timer.jsm");
+const { setTimeout, clearTimeout } = ChromeUtils.import(
+  "resource://gre/modules/Timer.jsm"
+);
 
 var EnigmailTimer = {
   /**
    * wait a defined number of miliseconds, then call a callback function
    * asynchronously
    *
    * @param callbackFunction: Function - any function specification
    * @param sleepTimeMs:      Number - optional number of miliseconds to delay
    *                             (0 if not specified)
    *
    * @return Number: timeoutID
    */
-  setTimeout: function(callbackFunction, sleepTimeMs = 0) {
-
+  setTimeout(callbackFunction, sleepTimeMs = 0) {
     let timeoutID;
 
     function callbackWrapper() {
       callbackFunction();
       try {
         clearTimeout(timeoutID);
       } catch (ex) {}
     }
@@ -40,10 +38,10 @@ var EnigmailTimer = {
     return timeoutID;
   },
 
   /**
    * Cancel a timeout callback
    *
    * @param Number: timeoutID
    */
-  clearTimeout: clearTimeout
+  clearTimeout,
 };
--- a/mail/extensions/openpgp/content/modules/trust.jsm
+++ b/mail/extensions/openpgp/content/modules/trust.jsm
@@ -3,17 +3,19 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailTrust"];
 
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
 
 // trust flags according to GPG documentation:
 // - https://www.gnupg.org/documentation/manuals/gnupg.pdf
 // - sources: doc/DETAILS
 // In the order of trustworthy:
 //  ---------------------------------------------------------
 //  i = The key is invalid (e.g. due to a missing self-signature)
 //  n = The key is not valid / Never trust this key
@@ -37,78 +39,77 @@ const EnigmailLocale = ChromeUtils.impor
 //  ---------------------------------------------------------
 const TRUSTLEVELS_SORTED = "indDreg?o-qmfu";
 const TRUSTLEVELS_SORTED_IDX_UNKNOWN = 7; // index of '?'
 
 var EnigmailTrust = {
   /**
    * @return - |string| containing the order of trust/validity values
    */
-  trustLevelsSorted: function() {
+  trustLevelsSorted() {
     return TRUSTLEVELS_SORTED;
   },
 
   /**
    * @return - |boolean| whether the flag is invalid (neither unknown nor valid)
    */
-  isInvalid: function(flag) {
+  isInvalid(flag) {
     return TRUSTLEVELS_SORTED.indexOf(flag) < TRUSTLEVELS_SORTED_IDX_UNKNOWN;
   },
 
   /**
    * return a merged value of trust level "key disabled"
    *
    * @keyObj - |object| containing the key data
    *
    * @return - |string| containing the trust value or "D" for disabled keys
    */
-  getTrustCode: function(keyObj) {
-    if (keyObj.keyUseFor.indexOf("D") >= 0) {
+  getTrustCode(keyObj) {
+    if (keyObj.keyUseFor.includes("D")) {
       return "D";
     }
-    else {
-      return keyObj.keyTrust;
-    }
+
+    return keyObj.keyTrust;
   },
 
-  getTrustLabel: function(trustCode) {
+  getTrustLabel(trustCode) {
     let keyTrust;
     switch (trustCode) {
-      case 'q':
+      case "q":
         keyTrust = EnigmailLocale.getString("keyValid.unknown");
         break;
-      case 'i':
+      case "i":
         keyTrust = EnigmailLocale.getString("keyValid.invalid");
         break;
-      case 'd':
-      case 'D':
+      case "d":
+      case "D":
         keyTrust = EnigmailLocale.getString("keyValid.disabled");
         break;
-      case 'r':
+      case "r":
         keyTrust = EnigmailLocale.getString("keyValid.revoked");
         break;
-      case 'e':
+      case "e":
         keyTrust = EnigmailLocale.getString("keyValid.expired");
         break;
-      case 'n':
+      case "n":
         keyTrust = EnigmailLocale.getString("keyTrust.untrusted");
         break;
-      case 'm':
+      case "m":
         keyTrust = EnigmailLocale.getString("keyTrust.marginal");
         break;
-      case 'f':
+      case "f":
         keyTrust = EnigmailLocale.getString("keyTrust.full");
         break;
-      case 'u':
+      case "u":
         keyTrust = EnigmailLocale.getString("keyTrust.ultimate");
         break;
-      case 'g':
+      case "g":
         keyTrust = EnigmailLocale.getString("keyTrust.group");
         break;
-      case '-':
+      case "-":
         keyTrust = "-";
         break;
       default:
         keyTrust = "";
     }
     return keyTrust;
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/uris.jsm
+++ b/mail/extensions/openpgp/content/modules/uris.jsm
@@ -3,143 +3,165 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailURIs"];
 
-
-
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
 
 const messageIdList = {};
 const encryptedUris = [];
 
 var EnigmailURIs = {
-  createMessageURI: function(originalUrl, contentType, contentCharset, contentData, persist) {
-    EnigmailLog.DEBUG("enigmail.js: Enigmail.createMessageURI: " + originalUrl +
-      ", " + contentType + ", " + contentCharset + "\n");
+  createMessageURI(
+    originalUrl,
+    contentType,
+    contentCharset,
+    contentData,
+    persist
+  ) {
+    EnigmailLog.DEBUG(
+      "enigmail.js: Enigmail.createMessageURI: " +
+        originalUrl +
+        ", " +
+        contentType +
+        ", " +
+        contentCharset +
+        "\n"
+    );
 
     const messageId = "msg" + Math.floor(Math.random() * 1.0e9);
 
     messageIdList[messageId] = {
-      originalUrl: originalUrl,
-      contentType: contentType,
-      contentCharset: contentCharset,
-      contentData: contentData,
-      persist: persist
+      originalUrl,
+      contentType,
+      contentCharset,
+      contentData,
+      persist,
     };
 
     return "enigmail:message/" + messageId;
   },
 
-  deleteMessageURI: function(uri) {
+  deleteMessageURI(uri) {
     EnigmailLog.DEBUG("enigmail.js: Enigmail.deleteMessageURI: " + uri + "\n");
 
     const messageId = EnigmailData.extractMessageId(uri);
 
     if (!messageId) {
       return false;
     }
-    else {
-      return (delete messageIdList[messageId]);
-    }
+
+    return delete messageIdList[messageId];
   },
 
-  getMessageURI: function(messageId) {
+  getMessageURI(messageId) {
     return messageIdList[messageId];
   },
 
   /*
    * remember the fact a URI is encrypted
    *
    * @param String msgUri
    *
    * @return null
    */
-  rememberEncryptedUri: function(uri) {
+  rememberEncryptedUri(uri) {
     EnigmailLog.DEBUG("uris.jsm: rememberEncryptedUri: uri=" + uri + "\n");
-    if (encryptedUris.indexOf(uri) < 0) {
+    if (!encryptedUris.includes(uri)) {
       encryptedUris.push(uri);
     }
   },
 
   /*
    * unremember the fact a URI is encrypted
    *
    * @param String msgUri
    *
    * @return null
    */
-  forgetEncryptedUri: function(uri) {
+  forgetEncryptedUri(uri) {
     EnigmailLog.DEBUG("uris.jsm: forgetEncryptedUri: uri=" + uri + "\n");
     const pos = encryptedUris.indexOf(uri);
     if (pos >= 0) {
       encryptedUris.splice(pos, 1);
     }
   },
 
   /*
    * determine if a URI was remebered as encrypted
    *
    * @param String msgUri
    *
    * @return: Boolean true if yes, false otherwise
    */
-  isEncryptedUri: function(uri) {
+  isEncryptedUri(uri) {
     EnigmailLog.DEBUG("uris.jsm: isEncryptedUri: uri=" + uri + "\n");
-    return encryptedUris.indexOf(uri) >= 0;
+    return encryptedUris.includes(uri);
   },
 
-
   /**
    * Determine message number and folder from mailnews URI
    *
    * @param url - nsIURI object
    *
    * @return Object:
    *    - msgNum: String - the message number, or "" if no URI Scheme fits
    *    - folder: String - the folder (or newsgroup) name
    */
-  msgIdentificationFromUrl: function(url) {
-
+  msgIdentificationFromUrl(url) {
     // sample URLs in Thunderbird
     // Local folder: mailbox:///some/path/to/folder?number=359360
     // IMAP: imap://user@host:port/fetch>some>path>111
     // NNTP: news://some.host/some.service.com?group=some.group.name&key=3510
     // also seen: e.g. mailbox:///som/path/to/folder?number=4455522&part=1.1.2&filename=test.eml
     // mailbox:///...?number=4455522&part=1.1.2&filename=test.eml&type=application/x-message-display&filename=test.eml
     // imap://user@host:port>UID>some>path>10?header=filter&emitter=js&examineEncryptedParts=true
 
-    if (!url) return null;
+    if (!url) {
+      return null;
+    }
 
-    EnigmailLog.DEBUG("uris.jsm: msgIdentificationFromUrl: url.pathQueryRef=" + ("path" in url ? url.path : url.pathQueryRef) + "\n");
+    EnigmailLog.DEBUG(
+      "uris.jsm: msgIdentificationFromUrl: url.pathQueryRef=" +
+        ("path" in url ? url.path : url.pathQueryRef) +
+        "\n"
+    );
 
     let msgNum = "";
     let msgFolder = "";
 
-    let pathQueryRef = ("path" in url ? url.path : url.pathQueryRef);
+    let pathQueryRef = "path" in url ? url.path : url.pathQueryRef;
 
     if (url.schemeIs("mailbox")) {
       msgNum = pathQueryRef.replace(/(.*[?&]number=)([0-9]+)([^0-9].*)?/, "$2");
       msgFolder = pathQueryRef.replace(/\?.*/, "");
-    }
-    else if (url.schemeIs("imap")) {
+    } else if (url.schemeIs("imap")) {
       let p = unescape(pathQueryRef);
       msgNum = p.replace(/(.*>)([0-9]+)([^0-9].*)?/, "$2");
       msgFolder = p.replace(/\?.*$/, "").replace(/>[^>]+$/, "");
-    }
-    else if (url.schemeIs("news")) {
+    } else if (url.schemeIs("news")) {
       msgNum = pathQueryRef.replace(/(.*[?&]key=)([0-9]+)([^0-9].*)?/, "$2");
       msgFolder = pathQueryRef.replace(/(.*[?&]group=)([^&]+)(&.*)?/, "$2");
     }
 
-    EnigmailLog.DEBUG("uris.jsm: msgIdentificationFromUrl: msgNum=" + msgNum + " / folder=" + msgFolder + "\n");
+    EnigmailLog.DEBUG(
+      "uris.jsm: msgIdentificationFromUrl: msgNum=" +
+        msgNum +
+        " / folder=" +
+        msgFolder +
+        "\n"
+    );
 
     return {
-      msgNum: msgNum,
-      folder: msgFolder.toLowerCase()
+      msgNum,
+      folder: msgFolder.toLowerCase(),
     };
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/verify.jsm
+++ b/mail/extensions/openpgp/content/modules/verify.jsm
@@ -3,27 +3,32 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailVerifyAttachment"];
 
-
-
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
-
-
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 var EnigmailVerifyAttachment = {
-  attachment: function(verifyFile, sigFile) {
+  attachment(verifyFile, sigFile) {
     EnigmailLog.DEBUG("verify.jsm: EnigmailVerifyAttachment.attachment:\n");
 
-    const verifyFilePath = EnigmailFiles.getEscapedFilename(EnigmailFiles.getFilePathReadonly(verifyFile.QueryInterface(Ci.nsIFile)));
-    const sigFilePath = EnigmailFiles.getEscapedFilename(EnigmailFiles.getFilePathReadonly(sigFile.QueryInterface(Ci.nsIFile)));
+    const verifyFilePath = EnigmailFiles.getEscapedFilename(
+      EnigmailFiles.getFilePathReadonly(verifyFile.QueryInterface(Ci.nsIFile))
+    );
+    const sigFilePath = EnigmailFiles.getEscapedFilename(
+      EnigmailFiles.getFilePathReadonly(sigFile.QueryInterface(Ci.nsIFile))
+    );
     const cApi = EnigmailCryptoAPI();
     return cApi.verifyAttachment(verifyFilePath, sigFilePath);
-
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/versioning.jsm
+++ b/mail/extensions/openpgp/content/modules/versioning.jsm
@@ -1,88 +1,57 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailVersioning"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
-let vc = null;
-
-function getVersionComparator() {
-  if (vc === null) {
-    vc = Cc["@mozilla.org/xpcom/version-comparator;1"].getService(Ci.nsIVersionComparator);
-  }
-  return vc;
-}
-
-/*
- * getVersion retrieves a version from a string
- *
- * @param   String  output           - string to retrieve the version from
- * @param   String  executable       - string to print when a version is not parseable
- *
- * @return  String  versionResponse  - The first value that matches a version format
- */
-function getVersion(output, executable) {
-  const m = output.match(/\b(\d+\.\d+\.\d+)\b/);
-  if (m) {
-    const versionResponse = m[1];
-
-    EnigmailLog.DEBUG(executable + " version found: " + versionResponse + "\n");
-
-    return versionResponse;
-  }
-  else {
-    return null;
-  }
-}
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 function greaterThanOrEqual(versionWeHave, versionWeAreComparingWith) {
-  return getVersionComparator().compare(versionWeHave, versionWeAreComparingWith) >= 0;
+  return Services.vc.compare(versionWeHave, versionWeAreComparingWith) >= 0;
 }
 
 function greaterThan(versionWeHave, versionWeAreComparingWith) {
-  return getVersionComparator().compare(versionWeHave, versionWeAreComparingWith) > 0;
+  return Services.vc.compare(versionWeHave, versionWeAreComparingWith) > 0;
 }
 
 function lessThan(versionWeHave, versionWeAreComparingWith) {
-  return getVersionComparator().compare(versionWeHave, versionWeAreComparingWith) < 0;
+  return Services.vc.compare(versionWeHave, versionWeAreComparingWith) < 0;
 }
 
 var EnigmailVersioning = {
   /**
    * Uses Mozilla's Version Comparator Component to identify whether the version
    * we have is greater than or equal to the version we are comparing with
    *
    * @param     String  versionWeHave               - version we have
    * @param     String  versionWeAreComparingWith   - version we want to compare with
    *
    * @return    Boolean     - The result of versionWeHave >= versionWeAreComparingWith
    */
-  greaterThanOrEqual: greaterThanOrEqual,
+  greaterThanOrEqual,
   /**
    * Uses Mozilla's Version Comparator Component to identify whether the version
    * we have is greater than the version we are comparing with
    *
    * @param     String  versionWeHave               - version we have
    * @param     String  versionWeAreComparingWith   - version we want to compare with
    *
    * @return    Boolean     - The result of versionWeHave > versionWeAreComparingWith
    */
-  greaterThan: greaterThan,
+  greaterThan,
   /**
    * Uses Mozilla's Version Comparator Component to identify whether the version
    * we have is less than the version we are comparing with
    *
    * @param     String  versionWeHave               - version we have
    * @param     String  versionWeAreComparingWith   - version we want to compare with
    *
    * @return    Boolean     - The result of versionWeHave < versionWeAreComparingWith
    */
-  lessThan: lessThan,
+  lessThan,
 };
--- a/mail/extensions/openpgp/content/modules/webKey.jsm
+++ b/mail/extensions/openpgp/content/modules/webKey.jsm
@@ -9,87 +9,88 @@
 /**
  * This module serves to integrate WKS (Webkey service) into Enigmail
  */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailWks"];
 
-
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-const EnigmailMimeEncrypt = ChromeUtils.import("chrome://openpgp/content/modules/mimeEncrypt.jsm").EnigmailMimeEncrypt;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-
-const GPG_WKS_CLIENT = "gpg-wks-client";
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+const EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
 
 var EnigmailWks = {
   wksClientPath: null,
 
   /**
    * Get WKS Client path (gpg-wks-client)
    *
    * @param window  : Object - parent window for dialog display
    * @param cb      : Function(retValue) - callback function.
    *                   retValue: nsIFile Object to gpg-wks-client executable or NULL
    * @return        : Object - NULL or a process handle
    */
-  getWksClientPathAsync: function(window, cb) {
+  getWksClientPathAsync(window, cb) {
     EnigmailLog.DEBUG("webKey.jsm: getWksClientPathAsync\n");
     throw new Error("Not implemented");
   },
 
   /**
    * Determine if WKS is supported by email provider
    *
    * @param email : String - user's email address
    * @param window: Object - parent window of dialog display
    * @param cb    : Function(retValue) - callback function.
    *                   retValue: Boolean: true if WKS is supported / false otherwise
    * @return      : Object - process handle
    */
-  isWksSupportedAsync: function(email, window, cb) {
-    EnigmailLog.DEBUG("webKey.jsm: isWksSupportedAsync: email = " + email + "\n");
+  isWksSupportedAsync(email, window, cb) {
+    EnigmailLog.DEBUG(
+      "webKey.jsm: isWksSupportedAsync: email = " + email + "\n"
+    );
     throw new Error("Not implemented");
   },
 
-
   /**
    * Submit a set of keys to the Web Key Server (WKD)
    *
    * @param keys:     Array of KeyObj
    * @param win:      parent Window for displaying dialogs
    * @param observer: Object (KeySrvListener API)
    *     Object implementing:
    *    - onProgress: function(percentComplete) [only implemented for download()]
    *     - onCancel: function() - the body will be set by the callee
    *
    * @return Promise<...>
    */
-  wksUpload: function(keys, win, observer = null) {
+  wksUpload(keys, win, observer = null) {
     EnigmailLog.DEBUG(`webKey.jsm: wksUpload(): keys = ${keys.length}\n`);
     let ids = getWkdIdentities(keys);
 
     if (observer === null) {
       observer = {
-        onProgress: function() {}
+        onProgress() {},
       };
     }
 
     observer.isCanceled = false;
     observer.onCancel = function() {
       this.isCanceled = true;
     };
 
-    if (!ids) throw new Error("error");
+    if (!ids) {
+      throw new Error("error");
+    }
 
     if (ids.senderIdentities.length === 0) {
       return new Promise(resolve => {
         resolve([]);
       });
     }
 
     return performWkdUpload(ids.senderIdentities, win, observer);
@@ -101,97 +102,79 @@ var EnigmailWks = {
    * @param ident : nsIMsgIdentity - user's ID
    * @param key   : Enigmail KeyObject of user's key
    * @param window: Object - parent window of dialog display
    * @param cb    : Function(retValue) - callback function.
    *                   retValue: Boolean: true if submit was successful / false otherwise
    * @return      : Object - process handle
    */
 
-  submitKey: function(ident, key, window, cb) {
+  submitKey(ident, key, window, cb) {
     EnigmailLog.DEBUG("webKey.jsm: submitKey(): email = " + ident.email + "\n");
     throw new Error("Not implemented");
   },
 
   /**
    * Submit a key to the email provider (= send publication request)
    *
    * @param ident : nsIMsgIdentity - user's ID
    * @param body  : String -  complete message source of the confirmation-request email obtained
    *                    from the email provider
    * @param window: Object - parent window of dialog display
    * @param cb    : Function(retValue) - callback function.
    *                   retValue: Boolean: true if submit was successful / false otherwise
    * @return      : Object - process handle
    */
 
-  confirmKey: function(ident, body, window, cb) {
+  confirmKey(ident, body, window, cb) {
     EnigmailLog.DEBUG("webKey.jsm: confirmKey: ident=" + ident.email + "\n");
     throw new Error("Not implemented");
-  }
+  },
 };
 
 /**
  * Check if a file exists and is executable
  *
  * @param path:         String - directory name
  * @param execFileName: String - executable name
  *
  * @return Object - nsIFile if file exists; NULL otherwise
  */
 
-function checkIfExists(path, execFileName) {
-  EnigmailLog.DEBUG("webKey.jsm checkIfExists() path=" + path + " execFileName=" + execFileName + "\n");
-
-  let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
-
-  execFileName = EnigmailFiles.potentialWindowsExecutable(execFileName);
-  EnigmailFiles.initPath(file, path);
-  file.append(execFileName);
-  if (file.exists() && file.isExecutable()) {
-    return file;
-  }
-  else {
-    return null;
-  }
-}
-
-
 function getWkdIdentities(keys) {
   EnigmailLog.DEBUG(`webKey.jsm: getWkdIdentities(): keys = ${keys.length}\n`);
   let senderIdentities = [],
     notFound = [];
 
   for (let key of keys) {
     try {
       let found = false;
       for (let uid of key.userIds) {
         let email = EnigmailFuncs.stripEmail(uid.userId);
         let maybeIdent = EnigmailStdlib.getIdentityForEmail(email);
 
         if (maybeIdent && maybeIdent.identity) {
           senderIdentities.push({
             identity: maybeIdent.identity,
-            fpr: key.fpr
+            fpr: key.fpr,
           });
         }
       }
       if (!found) {
         notFound.push(key);
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       EnigmailLog.DEBUG(ex + "\n");
       return null;
     }
   }
 
   return {
-    senderIdentities: senderIdentities,
-    notFound
+    senderIdentities,
+    notFound,
   };
 }
 
 /**
  * Do the WKD upload and interact with a progress receiver
  *
  * @param keyList:     Object:
  *                       - fprList (String - fingerprint)
@@ -201,75 +184,97 @@ function getWkdIdentities(keys) {
  *                       - onProgress: function(percentComplete [0 .. 100])
  *                             called after processing of every key (indpendent of status)
  *                       - onUpload: function(fpr)
  *                              called after successful uploading of a key
  *                       - onFinished: function(completionStatus, errorMessage, displayError)
  *                       - isCanceled: Boolean - used to determine if process is canceled
  */
 function performWkdUpload(keyList, win, observer) {
-  EnigmailLog.DEBUG(`webKey.jsm: performWkdUpload: keyList.length=${keyList.length}\n`);
+  EnigmailLog.DEBUG(
+    `webKey.jsm: performWkdUpload: keyList.length=${keyList.length}\n`
+  );
 
   let uploads = [];
 
   let numKeys = keyList.length;
 
   // For each key fpr/sender identity pair, check whenever WKS is supported
   // Result is an array of booleans
   for (let i = 0; i < numKeys; i++) {
     let keyFpr = keyList[i].fpr;
     let senderIdent = keyList[i].identity;
 
-    let was_uploaded = new Promise(function _isSupported(resolve, reject) {
-      EnigmailLog.DEBUG("webKey.jsm: performWkdUpload: _isSupported(): ident=" + senderIdent.email + ", key=" + keyFpr + "\n");
-      EnigmailWks.isWksSupportedAsync(senderIdent.email, win, function(is_supported) {
+    let was_uploaded = new Promise(function(resolve, reject) {
+      EnigmailLog.DEBUG(
+        "webKey.jsm: performWkdUpload: _isSupported(): ident=" +
+          senderIdent.email +
+          ", key=" +
+          keyFpr +
+          "\n"
+      );
+      EnigmailWks.isWksSupportedAsync(senderIdent.email, win, function(
+        is_supported
+      ) {
         if (observer.isCanceled) {
           EnigmailLog.DEBUG("webKey.jsm: performWkdUpload: canceled by user\n");
           reject("canceled");
         }
 
-        EnigmailLog.DEBUG("webKey.jsm: performWkdUpload: ident=" + senderIdent.email + ", supported=" + is_supported + "\n");
+        EnigmailLog.DEBUG(
+          "webKey.jsm: performWkdUpload: ident=" +
+            senderIdent.email +
+            ", supported=" +
+            is_supported +
+            "\n"
+        );
         resolve(is_supported);
       });
-    }).then(function _submitKey(is_supported) {
-      EnigmailLog.DEBUG(`webKey.jsm: performWkdUpload: _submitKey ${is_supported}\n`);
+    }).then(function(is_supported) {
+      EnigmailLog.DEBUG(
+        `webKey.jsm: performWkdUpload: _submitKey ${is_supported}\n`
+      );
       if (is_supported) {
-
         return new Promise(function(resolve, reject) {
-          EnigmailWks.submitKey(senderIdent, {
-            'fpr': keyFpr
-          }, win, function(success) {
-            observer.onProgress((i + 1) / numKeys * 100);
-            if (success) {
-              resolve(senderIdent);
+          EnigmailWks.submitKey(
+            senderIdent,
+            {
+              fpr: keyFpr,
+            },
+            win,
+            function(success) {
+              observer.onProgress(((i + 1) / numKeys) * 100);
+              if (success) {
+                resolve(senderIdent);
+              } else {
+                reject("submitFailed");
+              }
             }
-            else {
-              reject("submitFailed");
-            }
-          });
+          );
         });
       }
-      else {
-        observer.onProgress((i + 1) / numKeys * 100);
-        return Promise.resolve(null);
-      }
+
+      observer.onProgress(((i + 1) / numKeys) * 100);
+      return Promise.resolve(null);
     });
 
     uploads.push(was_uploaded);
   }
 
-  return Promise.all(uploads).catch(function(reason) {
-    //let errorMsg = EnigmailLocale.getString("keyserverProgress.wksUploadFailed");
-    return [];
-  }).then(function(senders) {
-    let uploaded_uids = [];
-    if (senders) {
-      senders.forEach(function(val) {
-        if (val !== null) {
-          uploaded_uids.push(val.email);
-        }
-      });
-    }
-    observer.onProgress(100);
+  return Promise.all(uploads)
+    .catch(function(reason) {
+      //let errorMsg = EnigmailLocale.getString("keyserverProgress.wksUploadFailed");
+      return [];
+    })
+    .then(function(senders) {
+      let uploaded_uids = [];
+      if (senders) {
+        senders.forEach(function(val) {
+          if (val !== null) {
+            uploaded_uids.push(val.email);
+          }
+        });
+      }
+      observer.onProgress(100);
 
-    return uploaded_uids;
-  });
+      return uploaded_uids;
+    });
 }
--- a/mail/extensions/openpgp/content/modules/windows.jsm
+++ b/mail/extensions/openpgp/content/modules/windows.jsm
@@ -3,108 +3,120 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailWindows"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailRules = ChromeUtils.import("chrome://openpgp/content/modules/rules.jsm").EnigmailRules;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
-const APPSHELL_MEDIATOR_CONTRACTID = "@mozilla.org/appshell/window-mediator;1";
-const APPSHSVC_CONTRACTID = "@mozilla.org/appshell/appShellService;1";
-
-const LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";
-const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailRules = ChromeUtils.import(
+  "chrome://openpgp/content/modules/rules.jsm"
+).EnigmailRules;
+const EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
 
 var EnigmailWindows = {
   /**
    * Display the OpenPGP setup wizard window
    *
    * win      : nsIWindow - the parent window
    * skipIntro: Boolean   - optional, if true, skip the introduction page
    *
    * no return value
    */
-  openSetupWizard: function(win, setupType) {
+  openSetupWizard(win, setupType) {
     EnigmailLog.DEBUG("windows.jsm: openSetupWizard()\n");
 
     if (!EnigmailStdlib.hasConfiguredAccounts()) {
-      EnigmailLog.DEBUG("windows.jsm: openSetupWizard: no configured accounts\n");
+      EnigmailLog.DEBUG(
+        "windows.jsm: openSetupWizard: no configured accounts\n"
+      );
       return;
     }
 
-    win.open("chrome://openpgp/content/ui/setupWizard2.xhtml",
-      "", "chrome,centerscreen,resizable");
+    win.open(
+      "chrome://openpgp/content/ui/setupWizard2.xhtml",
+      "",
+      "chrome,centerscreen,resizable"
+    );
   },
 
   /**
    * Open a window, or focus it if it is already open
    *
    * @winName   : String - name of the window; used to identify if it is already open
    * @spec      : String - window URL (e.g. chrome://openpgp/content/ui/test.xhtml)
    * @winOptions: String - window options as defined in nsIWindow.open
    * @optObj    : any    - an Object, Array, String, etc. that is passed as parameter
    *                       to the window
    */
-  openWin: function(winName, spec, winOptions, optObj) {
-    var windowManager = Cc[APPSHELL_MEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+  openWin(winName, spec, winOptions, optObj) {
+    var windowManager = Services.wm;
 
     var recentWin = null;
     for (let win of windowManager.getEnumerator(null)) {
       if (win.location.href == spec) {
         recentWin = win;
         break;
       }
       if (winName && win.name && win.name == winName) {
         win.focus();
         break;
       }
-
     }
 
     if (recentWin) {
       recentWin.focus();
-    }
-    else {
-      var appShellSvc = Cc[APPSHSVC_CONTRACTID].getService(Ci.nsIAppShellService);
+    } else {
+      var appShellSvc = Services.appShell;
       var domWin = appShellSvc.hiddenDOMWindow;
       try {
         domWin.open(spec, winName, "chrome," + winOptions, optObj);
-      }
-      catch (ex) {
+      } catch (ex) {
         domWin = windowManager.getMostRecentWindow(null);
         domWin.open(spec, winName, "chrome," + winOptions, optObj);
       }
     }
   },
 
   /**
    * Determine the best possible window to serve as parent window for dialogs.
    *
    * @return: nsIWindow object
    */
-  getBestParentWin: function() {
-    var windowManager = Cc[APPSHELL_MEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+  getBestParentWin() {
+    var windowManager = Services.wm;
 
     var bestFit = null;
 
     for (let win of windowManager.getEnumerator(null)) {
       if (win.location.href.search(/\/messenger.xhtml$/) > 0) {
         bestFit = win;
       }
-      if (!bestFit && win.location.href.search(/\/messengercompose.xhtml$/) > 0) {
+      if (
+        !bestFit &&
+        win.location.href.search(/\/messengercompose.xhtml$/) > 0
+      ) {
         bestFit = win;
       }
     }
 
     if (!bestFit) {
       var winEnum = windowManager.getEnumerator(null);
       bestFit = winEnum.getNext();
     }
@@ -116,531 +128,614 @@ var EnigmailWindows = {
    * Iterate through the frames of a window and return the first frame with a
    * matching name.
    *
    * @win:       nsIWindow - XUL window to search
    * @frameName: String    - name of the frame to seach
    *
    * @return:    the frame object or null if not found
    */
-  getFrame: function(win, frameName) {
+  getFrame(win, frameName) {
     EnigmailLog.DEBUG("windows.jsm: getFrame: name=" + frameName + "\n");
     for (var j = 0; j < win.frames.length; j++) {
       if (win.frames[j].name == frameName) {
         return win.frames[j];
       }
     }
     return null;
   },
 
-  getMostRecentWindow: function() {
-    var windowManager = Cc[APPSHELL_MEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+  getMostRecentWindow() {
+    var windowManager = Services.wm;
     return windowManager.getMostRecentWindow(null);
   },
 
-
   /**
    * Display the key help window
    *
    * @source - |string| containing the name of the file to display
    *
    * no return value
    */
 
-  openHelpWindow: function(source) {
-    EnigmailWindows.openWin("enigmail:help",
+  openHelpWindow(source) {
+    EnigmailWindows.openWin(
+      "enigmail:help",
       "chrome://openpgp/content/ui/enigmailHelp.xhtml?src=" + source,
-      "centerscreen,resizable");
+      "centerscreen,resizable"
+    );
   },
 
   /**
    * Display the "About Enigmail" window
    *
    * no return value
    */
-  openAboutWindow: function() {
-    EnigmailWindows.openMailTab("chrome://openpgp/content/ui/aboutEnigmail.html");
+  openAboutWindow() {
+    EnigmailWindows.openMailTab(
+      "chrome://openpgp/content/ui/aboutEnigmail.html"
+    );
   },
 
   /**
    * Open the Enigmail Documentation page in a new window
    *
    * no return value
    */
-  openEnigmailDocu: function(parent) {
+  openEnigmailDocu(parent) {
     if (!parent) {
       parent = this.getMostRecentWindow();
     }
 
-    parent.open("https://doesnotexist-openpgp-integration.thunderbird/faq/docu.php", "", "chrome,width=600,height=500,resizable");
+    parent.open(
+      "https://doesnotexist-openpgp-integration.thunderbird/faq/docu.php",
+      "",
+      "chrome,width=600,height=500,resizable"
+    );
   },
 
   /**
    * Display the Per-Recipient Rules editor window
    *
    * no return value
    */
-  openRulesEditor: function() {
-    EnigmailWindows.openWin("enigmail:rulesEditor",
+  openRulesEditor() {
+    EnigmailWindows.openWin(
+      "enigmail:rulesEditor",
       "chrome://openpgp/content/ui/enigmailRulesEditor.xhtml",
-      "dialog,centerscreen,resizable");
+      "dialog,centerscreen,resizable"
+    );
   },
 
   /**
    * Display the OpenPGP key manager window
    *
    * no return value
    */
-  openKeyManager: function(win) {
+  openKeyManager(win) {
     EnigmailCore.getService(win);
 
-    EnigmailWindows.openWin("enigmail:KeyManager",
+    EnigmailWindows.openWin(
+      "enigmail:KeyManager",
       "chrome://openpgp/content/ui/enigmailKeyManager.xhtml",
-      "resizable");
+      "resizable"
+    );
   },
 
   /**
    * Display the OpenPGP key manager window
    *
    * no return value
    */
-  openImportSettings: function(win) {
+  openImportSettings(win) {
     EnigmailCore.getService(win);
 
-    EnigmailWindows.openWin("",
+    EnigmailWindows.openWin(
+      "",
       "chrome://openpgp/content/ui/importSettings.xhtml",
-      "chrome,dialog,centerscreen,resizable,modal");
+      "chrome,dialog,centerscreen,resizable,modal"
+    );
   },
 
   /**
    * If the Key Manager is open, dispatch an event to tell the key
    * manager to refresh the displayed keys
    */
 
-  keyManReloadKeys: function() {
-    let windowManager = Cc[APPSHELL_MEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+  keyManReloadKeys() {
+    let windowManager = Services.wm;
     const winName = "enigmail:KeyManager";
     const spec = "chrome://openpgp/content/ui/enigmailKeygen.xhtml";
 
-    let recentWin = null;
     for (let thisWin of windowManager.getEnumerator(null)) {
       if (thisWin.location.href == spec) {
-        recentWin = thisWin;
         break;
       }
       if (thisWin.name && thisWin.name == winName) {
         let evt = new thisWin.Event("reload-keycache", {
-          "bubbles": true,
-          "cancelable": false
+          bubbles: true,
+          cancelable: false,
         });
         thisWin.dispatchEvent(evt);
         break;
       }
     }
   },
 
   /**
    * Display the key creation window
    *
    * no return value
    */
-  openKeyGen: function() {
-    EnigmailWindows.openWin("enigmail:generateKey",
+  openKeyGen() {
+    EnigmailWindows.openWin(
+      "enigmail:generateKey",
       "chrome://openpgp/content/ui/enigmailKeygen.xhtml",
-      "chrome,resizable=yes");
+      "chrome,resizable=yes"
+    );
   },
 
   /**
    * Display the card details window
    *
    * no return value
    */
-  openCardDetails: function() {
-    EnigmailWindows.openWin("enigmail:cardDetails",
+  openCardDetails() {
+    EnigmailWindows.openWin(
+      "enigmail:cardDetails",
       "chrome://openpgp/content/ui/enigmailCardDetails.xhtml",
-      "centerscreen");
+      "centerscreen"
+    );
   },
 
-
   /**
    * Display the console log window
    *
    * @win       - |object| holding the parent window for the dialog
    *
    * no return value
    */
-  openConsoleWindow: function() {
-    EnigmailWindows.openWin("enigmail:console",
+  openConsoleWindow() {
+    EnigmailWindows.openWin(
+      "enigmail:console",
       "chrome://openpgp/content/ui/enigmailConsole.xhtml",
-      "resizable,centerscreen");
+      "resizable,centerscreen"
+    );
   },
 
   /**
    * Display the window for the debug log file
    *
    * @win       - |object| holding the parent window for the dialog
    *
    * no return value
    */
-  openDebugLog: function(win) {
-    EnigmailWindows.openWin("enigmail:logFile",
-      "chrome://openpgp/content/ui/enigmailViewFile.xhtml?viewLog=1&title=" + escape(EnigmailLocale.getString("debugLog.title")),
-      "centerscreen");
+  openDebugLog(win) {
+    EnigmailWindows.openWin(
+      "enigmail:logFile",
+      "chrome://openpgp/content/ui/enigmailViewFile.xhtml?viewLog=1&title=" +
+        escape(EnigmailLocale.getString("debugLog.title")),
+      "centerscreen"
+    );
   },
 
   /**
    * Display the preferences dialog
    *
    * @win       - |object| holding the parent window for the dialog
    * @showBasic - |boolean| true if only the 1st page of the preferences window
    *              should be displayed / false otherwise
    * @selectTab - |string| ID of the tab element (in XUL) to display when opening
    *
    * no return value
    */
-  openPrefWindow: function(win, showBasic, selectTab) {
+  openPrefWindow(win, showBasic, selectTab) {
     EnigmailLog.DEBUG("windows.js: openPrefWindow\n");
 
     EnigmailCore.getService(win, true); // true: starting preferences dialog
 
     let url;
 
     url = "chrome://openpgp/content/ui/pref-enigmail.xhtml";
-    win.openDialog(url,
-      "_blank", "chrome,resizable=yes", {
-        'showBasic': showBasic,
-        'clientType': 'thunderbird',
-        'selectTab': selectTab
-      });
+    win.openDialog(url, "_blank", "chrome,resizable=yes", {
+      showBasic,
+      clientType: "thunderbird",
+      selectTab,
+    });
   },
 
   /**
    * Display the dialog for creating a new per-recipient rule
    *
    * @win          - |object| holding the parent window for the dialog
    * @emailAddress - |string| containing the email address for the rule
    *
    * @return       - always true
    */
-  createNewRule: function(win, emailAddress) {
+  createNewRule(win, emailAddress) {
     // make sure the rules database is loaded
     const enigmailSvc = EnigmailCore.getService(win);
     if (!enigmailSvc) {
       return false;
     }
 
     // open rule dialog
     EnigmailRules.getRulesData({});
 
     const inputObj = {
       toAddress: "{" + emailAddress + "}",
       options: "",
-      command: "add"
+      command: "add",
     };
-    win.openDialog("chrome://openpgp/content/ui/enigmailSingleRcptSettings.xhtml", "",
-      "dialog,modal,centerscreen,resizable", inputObj, {});
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailSingleRcptSettings.xhtml",
+      "",
+      "dialog,modal,centerscreen,resizable",
+      inputObj,
+      {}
+    );
     return true;
   },
 
   /**
    * Display the dialog for changing the expiry date of one or several keys
    *
    * @win        - |object| holding the parent window for the dialog
    * @userIdArr  - |array| of |strings| containing the User IDs
    * @keyIdArr   - |array| of |strings| containing the key IDs (eg. "0x12345678") to change
    *
    * @return  Boolean - true if expiry date was changed; false otherwise
    */
-  editKeyExpiry: function(win, userIdArr, keyIdArr) {
+  editKeyExpiry(win, userIdArr, keyIdArr) {
     const inputObj = {
       keyId: keyIdArr,
-      userId: userIdArr
+      userId: userIdArr,
     };
     const resultObj = {
-      refresh: false
+      refresh: false,
     };
-    win.openDialog("chrome://openpgp/content/ui/enigmailEditKeyExpiryDlg.xhtml", "",
-      "dialog,modal,centerscreen,resizable", inputObj, resultObj);
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailEditKeyExpiryDlg.xhtml",
+      "",
+      "dialog,modal,centerscreen,resizable",
+      inputObj,
+      resultObj
+    );
     return resultObj.refresh;
   },
 
   /**
    * Display the dialog for changing key trust of one or several keys
    *
    * @win        - |object| holding the parent window for the dialog
    * @userIdArr  - |array| of |strings| containing the User IDs
    * @keyIdArr   - |array| of |strings| containing the key IDs (eg. "0x12345678") to change
    *
    * @return  Boolean - true if key trust was changed; false otherwise
    */
-  editKeyTrust: function(win, userIdArr, keyIdArr) {
+  editKeyTrust(win, userIdArr, keyIdArr) {
     const inputObj = {
       keyId: keyIdArr,
-      userId: userIdArr
+      userId: userIdArr,
     };
     const resultObj = {
-      refresh: false
+      refresh: false,
     };
-    win.openDialog("chrome://openpgp/content/ui/enigmailEditKeyTrustDlg.xhtml", "",
-      "dialog,modal,centerscreen,resizable", inputObj, resultObj);
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailEditKeyTrustDlg.xhtml",
+      "",
+      "dialog,modal,centerscreen,resizable",
+      inputObj,
+      resultObj
+    );
     return resultObj.refresh;
   },
 
-
   /**
    * Display the dialog for signing a key
    *
    * @win        - |object| holding the parent window for the dialog
    * @userId     - |string| containing the User ID (for displaing in the dialog only)
    * @keyId      - |string| containing the key ID (eg. "0x12345678")
    *
    * @return  Boolean - true if key was signed; false otherwise
    */
-  signKey: function(win, userId, keyId) {
+  signKey(win, userId, keyId) {
     const inputObj = {
-      keyId: keyId,
-      userId: userId
+      keyId,
+      userId,
     };
     const resultObj = {
-      refresh: false
+      refresh: false,
     };
-    win.openDialog("chrome://openpgp/content/ui/enigmailSignKeyDlg.xhtml", "",
-      "dialog,modal,centerscreen,resizable", inputObj, resultObj);
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailSignKeyDlg.xhtml",
+      "",
+      "dialog,modal,centerscreen,resizable",
+      inputObj,
+      resultObj
+    );
     return resultObj.refresh;
   },
 
   /**
    * Display the photo ID associated with a key
    *
    * @win        - |object| holding the parent window for the dialog
    * @keyId      - |string| containing the key ID (eg. "0x12345678")
    * @userId     - |string| containing the User ID (for displaing in the dialog only)
    * @photoNumber - |number| UAT entry in the squence of appearance in the key listing, starting with 0
    * no return value
    */
-  showPhoto: function(win, keyId, userId, photoNumber) {
+  showPhoto(win, keyId, userId, photoNumber) {
     const enigmailSvc = EnigmailCore.getService(win);
     if (enigmailSvc) {
-      if (!photoNumber) photoNumber = 0;
+      if (!photoNumber) {
+        photoNumber = 0;
+      }
       let keyObj = EnigmailKeyRing.getKeyById(keyId);
       if (!keyObj) {
-        EnigmailWindows.alert(win, EnigmailLocale.getString("noPhotoAvailable"));
+        EnigmailWindows.alert(
+          win,
+          EnigmailLocale.getString("noPhotoAvailable")
+        );
       }
 
       let photoFile = keyObj.getPhotoFile(photoNumber);
 
       if (photoFile) {
         if (!(photoFile.isFile() && photoFile.isReadable())) {
-          EnigmailWindows.alert(win, EnigmailLocale.getString("error.photoPathNotReadable", photoFile.path));
-        }
-        else {
-          const photoUri = Cc[IOSERVICE_CONTRACTID].getService(Ci.nsIIOService).
-          newFileURI(photoFile).spec;
+          EnigmailWindows.alert(
+            win,
+            EnigmailLocale.getString(
+              "error.photoPathNotReadable",
+              photoFile.path
+            )
+          );
+        } else {
+          const photoUri = Services.io.newFileURI(photoFile).spec;
           const argsObj = {
-            photoUri: photoUri,
-            userId: userId,
-            keyId: keyId
+            photoUri,
+            userId,
+            keyId,
           };
 
-          win.openDialog("chrome://openpgp/content/ui/enigmailDispPhoto.xhtml",
+          win.openDialog(
+            "chrome://openpgp/content/ui/enigmailDispPhoto.xhtml",
             photoUri,
             "chrome,modal,resizable,dialog,centerscreen",
-            argsObj);
+            argsObj
+          );
           try {
             // delete the photo file
             photoFile.remove(false);
-          }
-          catch (ex) {}
+          } catch (ex) {}
         }
-      }
-      else {
-        EnigmailWindows.alert(win, EnigmailLocale.getString("noPhotoAvailable"));
+      } else {
+        EnigmailWindows.alert(
+          win,
+          EnigmailLocale.getString("noPhotoAvailable")
+        );
       }
     }
   },
 
   /**
    * Display the OpenPGP Key Details window
    *
    * @win        - |object| holding the parent window for the dialog
    * @keyId      - |string| containing the key ID (eg. "0x12345678")
    * @refresh    - |boolean| if true, cache is cleared and the key data is loaded from GnuPG
    *
    * @return  Boolean - true:  keylist needs to be refreshed
    *                  - false: no need to refresh keylist
    */
-  openKeyDetails: function(win, keyId, refresh) {
-    const keyListObj = {};
-
+  openKeyDetails(win, keyId, refresh) {
     if (!win) {
       win = this.getBestParentWin();
     }
 
     keyId = keyId.replace(/^0x/, "");
 
     if (refresh) {
       EnigmailKeyRing.clearCache();
     }
 
     const inputObj = {
-      keyId: keyId
+      keyId,
     };
     const resultObj = {
-      refresh: false
+      refresh: false,
     };
-    win.openDialog("chrome://openpgp/content/ui/keyDetailsDlg.xhtml", "",
-      "dialog,modal,centerscreen,resizable", inputObj, resultObj);
+    win.openDialog(
+      "chrome://openpgp/content/ui/keyDetailsDlg.xhtml",
+      "",
+      "dialog,modal,centerscreen,resizable",
+      inputObj,
+      resultObj
+    );
     if (resultObj.refresh) {
       EnigmailKeyRing.clearCache();
     }
 
     return resultObj.refresh;
   },
 
   /**
    * Display the dialog to search and/or download key(s) from a keyserver
    *
    * @win        - |object| holding the parent window for the dialog
    * @inputObj   - |object| with member searchList (|string| containing the keys to search)
    * @resultObj  - |object| with member importedKeys (|number| containing the number of imporeted keys)
    *
    * no return value
    */
-  downloadKeys: function(win, inputObj, resultObj) {
-    EnigmailLog.DEBUG("windows.jsm: downloadKeys: searchList=" + inputObj.searchList + "\n");
+  downloadKeys(win, inputObj, resultObj) {
+    EnigmailLog.DEBUG(
+      "windows.jsm: downloadKeys: searchList=" + inputObj.searchList + "\n"
+    );
 
     resultObj.importedKeys = 0;
 
-    const ioService = Cc[IOSERVICE_CONTRACTID].getService(Ci.nsIIOService);
+    const ioService = Services.io;
     if (ioService && ioService.offline) {
       EnigmailWindows.alert(win, EnigmailLocale.getString("needOnline"));
       return;
     }
 
     let valueObj = {};
     if (inputObj.searchList) {
       valueObj = {
-        keyId: "<" + inputObj.searchList.join("> <") + ">"
+        keyId: "<" + inputObj.searchList.join("> <") + ">",
       };
     }
 
     const keysrvObj = {};
 
     if (inputObj.searchList && inputObj.autoKeyServer) {
       keysrvObj.value = inputObj.autoKeyServer;
-    }
-    else {
-      win.openDialog("chrome://openpgp/content/ui/enigmailKeyserverDlg.xhtml",
-        "", "dialog,modal,centerscreen", valueObj, keysrvObj);
+    } else {
+      win.openDialog(
+        "chrome://openpgp/content/ui/enigmailKeyserverDlg.xhtml",
+        "",
+        "dialog,modal,centerscreen",
+        valueObj,
+        keysrvObj
+      );
     }
 
     if (!keysrvObj.value) {
       return;
     }
 
     inputObj.keyserver = keysrvObj.value;
 
     if (!inputObj.searchList) {
-      const searchval = keysrvObj.email.
-      replace(/^(\s*)(.*)/, "$2").
-      replace(/\s+$/, ""); // trim spaces
+      const searchval = keysrvObj.email
+        .replace(/^(\s*)(.*)/, "$2")
+        .replace(/\s+$/, ""); // trim spaces
       // special handling to convert fingerprints with spaces into fingerprint without spaces
-      if (searchval.length == 49 && searchval.match(/^[0-9a-fA-F ]*$/) &&
-        searchval[4] == ' ' && searchval[9] == ' ' && searchval[14] == ' ' &&
-        searchval[19] == ' ' && searchval[24] == ' ' && searchval[29] == ' ' &&
-        searchval[34] == ' ' && searchval[39] == ' ' && searchval[44] == ' ') {
+      if (
+        searchval.length == 49 &&
+        searchval.match(/^[0-9a-fA-F ]*$/) &&
+        searchval[4] == " " &&
+        searchval[9] == " " &&
+        searchval[14] == " " &&
+        searchval[19] == " " &&
+        searchval[24] == " " &&
+        searchval[29] == " " &&
+        searchval[34] == " " &&
+        searchval[39] == " " &&
+        searchval[44] == " "
+      ) {
         inputObj.searchList = ["0x" + searchval.replace(/ /g, "")];
-      }
-      else if (searchval.length == 40 && searchval.match(/^[0-9a-fA-F ]*$/)) {
+      } else if (searchval.length == 40 && searchval.match(/^[0-9a-fA-F ]*$/)) {
         inputObj.searchList = ["0x" + searchval];
-      }
-      else if (searchval.length == 8 && searchval.match(/^[0-9a-fA-F]*$/)) {
+      } else if (searchval.length == 8 && searchval.match(/^[0-9a-fA-F]*$/)) {
         // special handling to add the required leading 0x when searching for keys
         inputObj.searchList = ["0x" + searchval];
-      }
-      else if (searchval.length == 16 && searchval.match(/^[0-9a-fA-F]*$/)) {
+      } else if (searchval.length == 16 && searchval.match(/^[0-9a-fA-F]*$/)) {
         inputObj.searchList = ["0x" + searchval];
-      }
-      else {
+      } else {
         inputObj.searchList = searchval.split(/[,; ]+/);
       }
     }
 
-    win.openDialog("chrome://openpgp/content/ui/enigmailSearchKey.xhtml",
-      "", "dialog,modal,centerscreen", inputObj, resultObj);
+    win.openDialog(
+      "chrome://openpgp/content/ui/enigmailSearchKey.xhtml",
+      "",
+      "dialog,modal,centerscreen",
+      inputObj,
+      resultObj
+    );
   },
 
   /**
    * Display Autocrypt Setup Passwd dialog.
    *
    * @param dlgMode:       String - dialog mode: "input" / "display"
    * @param passwdType:    String - type of password ("numeric9x4" / "generic")
    * @param password:      String - password or initial two digits of password
    *
    * @return String entered password (in input mode) or NULL
    */
-  autocryptSetupPasswd: function(window, dlgMode, passwdType = "numeric9x4", password) {
+  autocryptSetupPasswd(window, dlgMode, passwdType = "numeric9x4", password) {
     if (!window) {
       window = this.getBestParentWin();
     }
 
     let inputObj = {
       password: null,
-      passwdType: passwdType,
-      dlgMode: dlgMode
+      passwdType,
+      dlgMode,
     };
 
-    if (password) inputObj.initialPasswd = password;
+    if (password) {
+      inputObj.initialPasswd = password;
+    }
 
-    window.openDialog("chrome://openpgp/content/ui/autocryptSetupPasswd.xhtml",
-      "", "dialog,modal,centerscreen", inputObj);
+    window.openDialog(
+      "chrome://openpgp/content/ui/autocryptSetupPasswd.xhtml",
+      "",
+      "dialog,modal,centerscreen",
+      inputObj
+    );
 
     return inputObj.password;
   },
 
   /**
    * Display dialog to initiate the Autocrypt Setup Message.
    *
    */
-  inititateAcSetupMessage: function(window) {
+  inititateAcSetupMessage(window) {
     if (!window) {
       window = this.getBestParentWin();
     }
 
-    window.openDialog("chrome://openpgp/content/ui/autocryptInitiateBackup.xhtml",
-      "", "dialog,centerscreen");
+    window.openDialog(
+      "chrome://openpgp/content/ui/autocryptInitiateBackup.xhtml",
+      "",
+      "dialog,centerscreen"
+    );
   },
 
   /**
    * Open a URL in a tab on the main window. The URL can either be a web page
    * (e.g. https://doesnotexist-openpgp-integration.thunderbird/ or a chrome document (e.g. chrome://openpgp/content/ui/x.xhtml))
    *
    * @param aURL:    String - the URL to open
    * @param winName: String - name of the window; used to identify if it is already open
    */
-  openMailTab: function(aURL, windowName) {
+  openMailTab(aURL, windowName) {
     let tabs = EnigmailStdlib.getMail3Pane().document.getElementById("tabmail");
 
     for (let i = 0; i < tabs.tabInfo.length; i++) {
-      if ("openedUrl" in tabs.tabInfo[i] && tabs.tabInfo[i].openedUrl.startsWith(aURL)) {
+      if (
+        "openedUrl" in tabs.tabInfo[i] &&
+        tabs.tabInfo[i].openedUrl.startsWith(aURL)
+      ) {
         tabs.switchToTab(i);
         return;
       }
     }
 
     let gotTab = tabs.openTab("chromeTab", {
-      chromePage: aURL
+      chromePage: aURL,
     });
     gotTab.openedUrl = aURL;
   },
 
-  shutdown: function(reason) {
+  shutdown(reason) {
     EnigmailLog.DEBUG("windows.jsm: shutdown()\n");
 
     let tabs = EnigmailStdlib.getMail3Pane().document.getElementById("tabmail");
 
     for (let i = tabs.tabInfo.length - 1; i >= 0; i--) {
-      if ("openedUrl" in tabs.tabInfo[i] && tabs.tabInfo[i].openedUrl.startsWith("chrome://openpgp/")) {
+      if (
+        "openedUrl" in tabs.tabInfo[i] &&
+        tabs.tabInfo[i].openedUrl.startsWith("chrome://openpgp/")
+      ) {
         tabs.closeTab(tabs.tabInfo[i]);
       }
     }
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/wkdLookup.jsm
+++ b/mail/extensions/openpgp/content/modules/wkdLookup.jsm
@@ -6,90 +6,220 @@
 
 /**
  *  Lookup keys by email addresses using WKD. A an email address is lookep up at most
  *  once a day. (see https://tools.ietf.org/html/draft-koch-openpgp-webkey-service)
  */
 
 var EXPORTED_SYMBOLS = ["EnigmailWkdLookup"];
 
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const PromiseUtils = ChromeUtils.import("resource://gre/modules/PromiseUtils.jsm").PromiseUtils;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailZBase32 = ChromeUtils.import("chrome://openpgp/content/modules/zbase32.jsm").EnigmailZBase32;
-const EnigmailOpenPGP = ChromeUtils.import("chrome://openpgp/content/modules/openpgp.jsm").EnigmailOpenPGP;
-const EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailSqliteDb = ChromeUtils.import("chrome://openpgp/content/modules/sqliteDb.jsm").EnigmailSqliteDb;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailZBase32 = ChromeUtils.import(
+  "chrome://openpgp/content/modules/zbase32.jsm"
+).EnigmailZBase32;
+const EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailSqliteDb = ChromeUtils.import(
+  "chrome://openpgp/content/modules/sqliteDb.jsm"
+).EnigmailSqliteDb;
 
-Components.utils.importGlobalProperties(["fetch"]);
+Cu.importGlobalProperties(["fetch"]);
 
 // Those domains are not expected to have WKD:
 var BLACKLIST_DOMAINS = [
   /* Default domains included */
-  "aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", "gmx.com", "googlemail.com",
-  "google.com", "hotmail.com", "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com",
-  "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk",
+  "aol.com",
+  "att.net",
+  "comcast.net",
+  "facebook.com",
+  "gmail.com",
+  "gmx.com",
+  "googlemail.com",
+  "google.com",
+  "hotmail.com",
+  "hotmail.co.uk",
+  "mac.com",
+  "me.com",
+  "mail.com",
+  "msn.com",
+  "live.com",
+  "sbcglobal.net",
+  "verizon.net",
+  "yahoo.com",
+  "yahoo.co.uk",
 
   /* Other global domains */
-  "email.com", "games.com" /* AOL */ , "gmx.net", "icloud.com",
-  "iname.com", "inbox.com", "lavabit.com", "love.com" /* AOL */ , "outlook.com", "pobox.com", "tutanota.de", "tutanota.com", "tutamail.com", "tuta.io",
-  "keemail.me", "rocketmail.com" /* Yahoo */ , "safe-mail.net", "wow.com" /* AOL */ , "ygm.com" /* AOL */ ,
-  "ymail.com" /* Yahoo */ , "zoho.com", "yandex.com",
+  "email.com",
+  "games.com" /* AOL */,
+  "gmx.net",
+  "icloud.com",
+  "iname.com",
+  "inbox.com",
+  "lavabit.com",
+  "love.com" /* AOL */,
+  "outlook.com",
+  "pobox.com",
+  "tutanota.de",
+  "tutanota.com",
+  "tutamail.com",
+  "tuta.io",
+  "keemail.me",
+  "rocketmail.com" /* Yahoo */,
+  "safe-mail.net",
+  "wow.com" /* AOL */,
+  "ygm.com" /* AOL */,
+  "ymail.com" /* Yahoo */,
+  "zoho.com",
+  "yandex.com",
 
   /* United States ISP domains */
-  "bellsouth.net", "charter.net", "cox.net", "earthlink.net", "juno.com",
+  "bellsouth.net",
+  "charter.net",
+  "cox.net",
+  "earthlink.net",
+  "juno.com",
 
   /* British ISP domains */
-  "btinternet.com", "virginmedia.com", "blueyonder.co.uk", "freeserve.co.uk", "live.co.uk",
-  "ntlworld.com", "o2.co.uk", "orange.net", "sky.com", "talktalk.co.uk", "tiscali.co.uk",
-  "virgin.net", "wanadoo.co.uk", "bt.com",
+  "btinternet.com",
+  "virginmedia.com",
+  "blueyonder.co.uk",
+  "freeserve.co.uk",
+  "live.co.uk",
+  "ntlworld.com",
+  "o2.co.uk",
+  "orange.net",
+  "sky.com",
+  "talktalk.co.uk",
+  "tiscali.co.uk",
+  "virgin.net",
+  "wanadoo.co.uk",
+  "bt.com",
 
   /* Domains used in Asia */
-  "sina.com", "sina.cn", "qq.com", "naver.com", "hanmail.net", "daum.net", "nate.com", "yahoo.co.jp", "yahoo.co.kr", "yahoo.co.id", "yahoo.co.in", "yahoo.com.sg", "yahoo.com.ph", "163.com", "yeah.net", "126.com", "21cn.com", "aliyun.com", "foxmail.com",
+  "sina.com",
+  "sina.cn",
+  "qq.com",
+  "naver.com",
+  "hanmail.net",
+  "daum.net",
+  "nate.com",
+  "yahoo.co.jp",
+  "yahoo.co.kr",
+  "yahoo.co.id",
+  "yahoo.co.in",
+  "yahoo.com.sg",
+  "yahoo.com.ph",
+  "163.com",
+  "yeah.net",
+  "126.com",
+  "21cn.com",
+  "aliyun.com",
+  "foxmail.com",
 
   /* French ISP domains */
-  "hotmail.fr", "live.fr", "laposte.net", "yahoo.fr", "wanadoo.fr", "orange.fr", "gmx.fr", "sfr.fr", "neuf.fr", "free.fr",
+  "hotmail.fr",
+  "live.fr",
+  "laposte.net",
+  "yahoo.fr",
+  "wanadoo.fr",
+  "orange.fr",
+  "gmx.fr",
+  "sfr.fr",
+  "neuf.fr",
+  "free.fr",
 
   /* German ISP domains */
-  "gmx.de", "hotmail.de", "live.de", "online.de", "t-online.de" /* T-Mobile */ , "web.de", "yahoo.de",
+  "gmx.de",
+  "hotmail.de",
+  "live.de",
+  "online.de",
+  "t-online.de" /* T-Mobile */,
+  "web.de",
+  "yahoo.de",
 
   /* Italian ISP domains */
-  "libero.it", "virgilio.it", "hotmail.it", "aol.it", "tiscali.it", "alice.it", "live.it", "yahoo.it", "email.it", "tin.it", "poste.it", "teletu.it",
+  "libero.it",
+  "virgilio.it",
+  "hotmail.it",
+  "aol.it",
+  "tiscali.it",
+  "alice.it",
+  "live.it",
+  "yahoo.it",
+  "email.it",
+  "tin.it",
+  "poste.it",
+  "teletu.it",
 
   /* Russian ISP domains */
-  "mail.ru", "rambler.ru", "yandex.ru", "ya.ru", "list.ru",
+  "mail.ru",
+  "rambler.ru",
+  "yandex.ru",
+  "ya.ru",
+  "list.ru",
 
   /* Belgian ISP domains */
-  "hotmail.be", "live.be", "skynet.be", "voo.be", "tvcablenet.be", "telenet.be",
+  "hotmail.be",
+  "live.be",
+  "skynet.be",
+  "voo.be",
+  "tvcablenet.be",
+  "telenet.be",
 
   /* Argentinian ISP domains */
-  "hotmail.com.ar", "live.com.ar", "yahoo.com.ar", "fibertel.com.ar", "speedy.com.ar", "arnet.com.ar",
+  "hotmail.com.ar",
+  "live.com.ar",
+  "yahoo.com.ar",
+  "fibertel.com.ar",
+  "speedy.com.ar",
+  "arnet.com.ar",
 
   /* Domains used in Mexico */
-  "yahoo.com.mx", "live.com.mx", "hotmail.es", "hotmail.com.mx", "prodigy.net.mx",
+  "yahoo.com.mx",
+  "live.com.mx",
+  "hotmail.es",
+  "hotmail.com.mx",
+  "prodigy.net.mx",
 
   /* Domains used in Canada */
-  "yahoo.ca", "hotmail.ca", "bell.net", "shaw.ca", "sympatico.ca", "rogers.com",
+  "yahoo.ca",
+  "hotmail.ca",
+  "bell.net",
+  "shaw.ca",
+  "sympatico.ca",
+  "rogers.com",
 
   /* Domains used in Brazil */
-  "yahoo.com.br", "hotmail.com.br", "outlook.com.br", "uol.com.br", "bol.com.br", "terra.com.br", "ig.com.br", "itelefonica.com.br", "r7.com", "zipmail.com.br", "globo.com", "globomail.com", "oi.com.br"
+  "yahoo.com.br",
+  "hotmail.com.br",
+  "outlook.com.br",
+  "uol.com.br",
+  "bol.com.br",
+  "terra.com.br",
+  "ig.com.br",
+  "itelefonica.com.br",
+  "r7.com",
+  "zipmail.com.br",
+  "globo.com",
+  "globomail.com",
+  "oi.com.br",
 ];
 
 var EnigmailWkdLookup = {
-
   /**
    * Try to import keys using WKD. Found keys are automatically imported
    *
    * @param {Array of String} emailList: email addresses (in lowercase)
    *
    * @return {Promise<Boolean>}: true - new keys found
    */
-  findKeys: function(emails) {
+  findKeys(emails) {
     return new Promise((resolve, reject) => {
       EnigmailLog.DEBUG("wkdLookup.jsm: findKeys(" + emails.join(",") + ")\n");
 
       if (emails.length === 0) {
         resolve(false);
         return;
       }
 
@@ -98,271 +228,330 @@ var EnigmailWkdLookup = {
       // do a little sanity test such that we don't do the lookup for nothing too often
       for (let e of emails) {
         if (e.search(/.@.+\...+$/) < 0) {
           resolve(false);
           return;
         }
       }
 
-      Promise.all(emails.map(
-          function(mailAddr) {
-            return self.determineLastAttempt(mailAddr.trim().toLowerCase());
-          }))
+      Promise.all(
+        emails.map(function(mailAddr) {
+          return self.determineLastAttempt(mailAddr.trim().toLowerCase());
+        })
+      )
         .then(function(checks) {
           let toCheck = [];
 
-          EnigmailLog.DEBUG("wkdLookup.jsm: findKeys: checks " + checks.length + "\n");
+          EnigmailLog.DEBUG(
+            "wkdLookup.jsm: findKeys: checks " + checks.length + "\n"
+          );
 
           for (let i = 0; i < checks.length; i++) {
             if (checks[i]) {
-              EnigmailLog.DEBUG("wkdLookup.jsm: findKeys: recheck " + emails[i] + "\n");
+              EnigmailLog.DEBUG(
+                "wkdLookup.jsm: findKeys: recheck " + emails[i] + "\n"
+              );
               toCheck.push(emails[i]);
-            }
-            else {
-              EnigmailLog.DEBUG("wkdLookup.jsm: findKeys: skip check " + emails[i] + "\n");
+            } else {
+              EnigmailLog.DEBUG(
+                "wkdLookup.jsm: findKeys: skip check " + emails[i] + "\n"
+              );
             }
           }
 
           if (toCheck.length > 0) {
-
-            Promise.all(toCheck.map((email) => {
-              return self.downloadKey(email);
-            })).then((dataArr) => {
-
+            Promise.all(
+              toCheck.map(email => {
+                return self.downloadKey(email);
+              })
+            ).then(dataArr => {
               if (dataArr) {
                 let gotKeys = [];
                 for (let i = 0; i < dataArr.length; i++) {
                   if (dataArr[i] !== null) {
                     gotKeys.push(dataArr[i]);
                   }
                 }
 
                 if (gotKeys.length > 0) {
                   importDownloadedKeys(gotKeys);
                   resolve(true);
+                } else {
+                  resolve(false);
                 }
-                else
-                  resolve(false);
               }
             });
-          }
-          else {
+          } else {
             resolve(false);
           }
-
         })
         .catch(() => {
           resolve(false);
         });
     });
   },
 
   /**
    * Determine for an email address when we last attempted to
    * obtain a key via wkd
    *
    * @param {String} email: email address
    *
    * @return {Promise<Boolean>}: true if new WKD lookup required
    */
-  determineLastAttempt: async function(email) {
+  async determineLastAttempt(email) {
     EnigmailLog.DEBUG("wkdLookup.jsm: determineLastAttempt(" + email + ")\n");
 
     let conn;
     try {
       conn = await EnigmailSqliteDb.openDatabase();
       let val = await timeForRecheck(conn, email);
       conn.close();
       return val;
-    }
-    catch (x) {
-      EnigmailLog.DEBUG("wkdLookup.jsm: determineLastAttempt: could not open database\n");
+    } catch (x) {
+      EnigmailLog.DEBUG(
+        "wkdLookup.jsm: determineLastAttempt: could not open database\n"
+      );
       if (conn) {
-        EnigmailLog.DEBUG("wkdLookup.jsm: error - closing connection: " + x + "\n");
+        EnigmailLog.DEBUG(
+          "wkdLookup.jsm: error - closing connection: " + x + "\n"
+        );
         conn.close();
       }
     }
     // in case something goes wrong we recheck anyway
     return true;
   },
 
   /**
    * get the download URL for an email address for WKD or domain-specific locations
    *
    * @param {String} email: email address
    *
    * @return {Promise<String>}: URL (or null if not possible)
    */
 
-  getDownloadUrlFromEmail: async function(email, advancedMethod) {
+  async getDownloadUrlFromEmail(email, advancedMethod) {
     email = email.toLowerCase().trim();
 
     let url = await getSiteSpecificUrl(email);
-    if (url) return url;
+    if (url) {
+      return url;
+    }
 
     let at = email.indexOf("@");
 
     let domain = email.substr(at + 1);
     let user = email.substr(0, at);
 
-    var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
+    var converter = Cc[
+      "@mozilla.org/intl/scriptableunicodeconverter"
+    ].createInstance(Ci.nsIScriptableUnicodeConverter);
     converter.charset = "UTF-8";
     var data = converter.convertToByteArray(user, {});
 
-    var ch = Components.classes["@mozilla.org/security/hash;1"].createInstance(Components.interfaces.nsICryptoHash);
+    var ch = Cc["@mozilla.org/security/hash;1"].createInstance(
+      Ci.nsICryptoHash
+    );
     ch.init(ch.SHA1);
     ch.update(data, data.length);
     let gotHash = ch.finish(false);
     let encodedHash = EnigmailZBase32.encode(gotHash);
 
     if (advancedMethod) {
-      url = "https://openpgpkey." + domain + "/.well-known/openpgpkey/" + domain + "/hu/" + encodedHash + "?l=" + escape(user);
-    }
-    else {
-      url = "https://" + domain + "/.well-known/openpgpkey/hu/" + encodedHash + "?l=" + escape(user);
+      url =
+        "https://openpgpkey." +
+        domain +
+        "/.well-known/openpgpkey/" +
+        domain +
+        "/hu/" +
+        encodedHash +
+        "?l=" +
+        escape(user);
+    } else {
+      url =
+        "https://" +
+        domain +
+        "/.well-known/openpgpkey/hu/" +
+        encodedHash +
+        "?l=" +
+        escape(user);
     }
 
     return url;
   },
 
   /**
    * Download a key for an email address
    *
    * @param {String} email: email address
    *
    * @return {Promise<String>}: Key data (or null if not possible)
    */
-  downloadKey: async function(email) {
+  async downloadKey(email) {
     EnigmailLog.DEBUG("wkdLookup.jsm: downloadKey(" + email + ")\n");
 
     if (!this.isWkdAvailable(email)) {
       EnigmailLog.DEBUG("wkdLookup.jsm: downloadKey: no WKD for the domain\n");
       return null;
     }
 
     let keyData = await this.doWkdKeyDownload(email, true);
 
     if (!keyData) {
       keyData = await this.doWkdKeyDownload(email, false);
     }
 
     return keyData;
   },
 
-  doWkdKeyDownload: async function(email, advancedMethod) {
-    EnigmailLog.DEBUG(`wkdLookup.jsm: doWkdKeyDownload(${email}, ${advancedMethod})\n`);
+  async doWkdKeyDownload(email, advancedMethod) {
+    EnigmailLog.DEBUG(
+      `wkdLookup.jsm: doWkdKeyDownload(${email}, ${advancedMethod})\n`
+    );
 
-    let url = await EnigmailWkdLookup.getDownloadUrlFromEmail(email, advancedMethod);
+    let url = await EnigmailWkdLookup.getDownloadUrlFromEmail(
+      email,
+      advancedMethod
+    );
 
     let padLen = (url.length % 512) + 1;
     let hdrs = new Headers({
-      'Authorization': 'Basic ' + btoa("no-user:")
+      Authorization: "Basic " + btoa("no-user:"),
     });
-    hdrs.append('Content-Type', 'application/octet-stream');
-    hdrs.append('X-Enigmail-Padding', "x".padEnd(padLen, "x"));
+    hdrs.append("Content-Type", "application/octet-stream");
+    hdrs.append("X-Enigmail-Padding", "x".padEnd(padLen, "x"));
 
     let myRequest = new Request(url, {
-      method: 'GET',
+      method: "GET",
       headers: hdrs,
-      mode: 'cors',
+      mode: "cors",
       //redirect: 'error',
-      redirect: 'follow',
-      cache: 'default'
+      redirect: "follow",
+      cache: "default",
     });
 
     let response;
     try {
-      EnigmailLog.DEBUG("wkdLookup.jsm: doWkdKeyDownload: requesting " + url + "\n");
+      EnigmailLog.DEBUG(
+        "wkdLookup.jsm: doWkdKeyDownload: requesting " + url + "\n"
+      );
       response = await fetch(myRequest);
       if (!response.ok) {
         return null;
       }
-    }
-    catch (ex) {
-      EnigmailLog.DEBUG("wkdLookup.jsm: doWkdKeyDownload: error " + ex.toString() + "\n");
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "wkdLookup.jsm: doWkdKeyDownload: error " + ex.toString() + "\n"
+      );
       return null;
     }
 
     try {
-      if (response.headers.has("content-type") && response.headers.get("content-type").search(/^text\/html/i) === 0) {
+      if (
+        response.headers.has("content-type") &&
+        response.headers.get("content-type").search(/^text\/html/i) === 0
+      ) {
         // if we get HTML output, we return nothing (for example redirects to error catching pages)
         return null;
       }
-      let keyData = EnigmailData.arrayBufferToString(Cu.cloneInto(await response.arrayBuffer(), this));
-      EnigmailLog.DEBUG(`wkdLookup.jsm: doWkdKeyDownload: got data for ${email}\n`);
+      let keyData = EnigmailData.arrayBufferToString(
+        Cu.cloneInto(await response.arrayBuffer(), this)
+      );
+      EnigmailLog.DEBUG(
+        `wkdLookup.jsm: doWkdKeyDownload: got data for ${email}\n`
+      );
       return {
-        email: email,
-        keyData: keyData
+        email,
+        keyData,
       };
-    }
-    catch (ex) {
-      EnigmailLog.DEBUG("wkdLookup.jsm: doWkdKeyDownload: error " + ex.toString() + "\n");
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "wkdLookup.jsm: doWkdKeyDownload: error " + ex.toString() + "\n"
+      );
       return null;
     }
   },
 
-  isWkdAvailable: function(email) {
+  isWkdAvailable(email) {
     let domain = email.toLowerCase().replace(/^.*@/, "");
 
-    return (BLACKLIST_DOMAINS.indexOf(domain) < 0);
-  }
+    return !BLACKLIST_DOMAINS.includes(domain);
+  },
 };
 
-
 /**
  * Check if enough time has passed since we looked-up the key for "email".
  *
  * @param connection: Object - SQLite connection
  * @param email:      String - Email address to search (in lowercase)
  *
  * @return Promise (true if new lookup required)
  */
 function timeForRecheck(connection, email) {
   EnigmailLog.DEBUG("wkdLookup.jsm: timeForRecheck\n");
 
   let obj = {
-    email: email,
-    now: Date.now()
+    email,
+    now: Date.now(),
   };
 
-  return connection.execute(
-    "select count(*) from wkd_lookup_timestamp where email = :email and :now - last_seen < 60*60*24", obj
-  ).then(function(val) {
-    return connection.execute(
-      "insert or replace into wkd_lookup_timestamp values (:email, :now)", obj
-    ).then(function() {
-      return Promise.resolve(val);
-    });
-  }).then(function(rows) {
-    EnigmailLog.DEBUG("wkdLookup.jsm: timeForRecheck: " + rows.length + "\n");
+  return connection
+    .execute(
+      "select count(*) from wkd_lookup_timestamp where email = :email and :now - last_seen < 60*60*24",
+      obj
+    )
+    .then(function(val) {
+      return connection
+        .execute(
+          "insert or replace into wkd_lookup_timestamp values (:email, :now)",
+          obj
+        )
+        .then(function() {
+          return Promise.resolve(val);
+        });
+    })
+    .then(
+      function(rows) {
+        EnigmailLog.DEBUG(
+          "wkdLookup.jsm: timeForRecheck: " + rows.length + "\n"
+        );
 
-    return rows.length === 1 && rows[0].getResultByIndex(0) === 0;
-  }, function(error) {
-    EnigmailLog.DEBUG("wkdLookup.jsm: timeForRecheck - error" + error + "\n");
-    Promise.reject(error);
-  });
+        return rows.length === 1 && rows[0].getResultByIndex(0) === 0;
+      },
+      function(error) {
+        EnigmailLog.DEBUG(
+          "wkdLookup.jsm: timeForRecheck - error" + error + "\n"
+        );
+        Promise.reject(error);
+      }
+    );
 }
 
 /**
  * Import downloaded keys
  *
  * @param {Array of String}: ASCII armored or binary string
  *
  * no return value
  */
 function importDownloadedKeys(keysArr) {
+  throw new Error("Not implemented");
+
+  /*
   EnigmailLog.DEBUG("wkdLookup.jsm: importDownloadedKeys(" + keysArr.length + ")\n");
 
   let keyData = "";
   let domainArr = [];
   for (let k in keysArr) {
     if (keysArr[k]) {
       if (keysArr[k].keyData.search(/^-----BEGIN PGP PUBLIC KEY BLOCK-----/) < 0) {
         try {
+          // TODO: need a MPL version of bytesToArmor
           keyData += EnigmailOpenPGP.enigmailFuncs.bytesToArmor(EnigmailOpenPGP.armor.public_key, keysArr[k].keyData);
         }
         catch (ex) {
           EnigmailLog.DEBUG("wkdLookup.jsm: importDownloadedKeys: exeption=" + ex + "\n");
         }
       }
       else {
         keyData += keysArr[k].keyData;
@@ -374,16 +563,17 @@ function importDownloadedKeys(keysArr) {
 
   let keyList = EnigmailKey.getKeyListFromKeyBlock(keyData, {}, false);
 
   for (let k in keyList) {
     EnigmailLog.DEBUG("wkdLookup.jsm: importDownloadedKeys: fpr=" + keyList[k].fpr + "\n");
   }
 
   EnigmailKeyRing.importKey(null, false, keyData, "", {}, {}, false, domainArr);
+  */
 }
 
 /**
  * Get special URLs for specific sites that don't use WKD, but still provide
  * public keys of their users in
  *
  * @param {String}: emailAddr: email address in lowercase
  *
@@ -392,22 +582,26 @@ function importDownloadedKeys(keysArr) {
 async function getSiteSpecificUrl(emailAddr) {
   let domain = emailAddr.replace(/^.+@/, "");
   let url = null;
 
   switch (domain) {
     case "protonmail.ch":
     case "protonmail.com":
     case "pm.me":
-      url = "https://api.protonmail.ch/pks/lookup?op=get&options=mr&search=" + escape(emailAddr);
+      url =
+        "https://api.protonmail.ch/pks/lookup?op=get&options=mr&search=" +
+        escape(emailAddr);
       break;
   }
 
   if (!url) {
-    throw new Error("EnigmailWkdLookup getSiteSpecificUrl with DNS not implemented");
+    throw new Error(
+      "EnigmailWkdLookup getSiteSpecificUrl with DNS not implemented"
+    );
     /*
     try {
       let mxHosts = await EnigmailDns.lookup("MX", domain);
       if (mxHosts & mxHosts.indexOf("mail.protonmail.ch") >= 0 ||
         mxHosts.indexOf("mailsec.protonmail.ch") >= 0) {
         url = "https://api.protonmail.ch/pks/lookup?op=get&options=mr&search=" + escape(emailAddr);
       }
     }
--- a/mail/extensions/openpgp/content/modules/wksMimeHandler.jsm
+++ b/mail/extensions/openpgp/content/modules/wksMimeHandler.jsm
@@ -1,230 +1,268 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 var EXPORTED_SYMBOLS = ["EnigmailWksMimeHandler"];
 
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+
 /**
  *  Module for handling response messages from OpenPGP Web Key Service
  */
 
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailVerify = ChromeUtils.import("chrome://openpgp/content/modules/mimeVerify.jsm").EnigmailVerify;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailDecryption = ChromeUtils.import("chrome://openpgp/content/modules/decryption.jsm").EnigmailDecryption;
-const EnigmailSingletons = ChromeUtils.import("chrome://openpgp/content/modules/singletons.jsm").EnigmailSingletons;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-
-const APPSHELL_MEDIATOR_CONTRACTID = "@mozilla.org/appshell/window-mediator;1";
+const EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailVerify = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mimeVerify.jsm"
+).EnigmailVerify;
+const EnigmailLog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailDecryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/decryption.jsm"
+).EnigmailDecryption;
+const EnigmailSingletons = ChromeUtils.import(
+  "chrome://openpgp/content/modules/singletons.jsm"
+).EnigmailSingletons;
+const EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
 
 var gDebugLog = false;
 
-
 var EnigmailWksMimeHandler = {
-
   /***
    * register a PGP/MIME verify object the same way PGP/MIME encrypted mail is handled
    */
-  registerContentTypeHandler: function() {
+  registerContentTypeHandler() {
     EnigmailLog.DEBUG("wksMimeHandler.jsm: registerContentTypeHandler()\n");
     let reg = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
 
-    let pgpMimeClass = Components.classes["@mozilla.org/mimecth;1?type=multipart/encrypted"];
+    let pgpMimeClass = Cc["@mozilla.org/mimecth;1?type=multipart/encrypted"];
 
     reg.registerFactory(
       pgpMimeClass,
       "Enigmail WKD Response Handler",
       "@mozilla.org/mimecth;1?type=application/vnd.gnupg.wks",
-      null);
+      null
+    );
   },
 
-  newHandler: function() {
+  newHandler() {
     EnigmailLog.DEBUG("wksMimeHandler.jsm: newHandler()\n");
 
     let v = new PgpWkdHandler();
     return v;
-  }
-
+  },
 };
 
 // MimeVerify Constructor
 function PgpWkdHandler(protocol) {
-  this.inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
+  this.inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+    Ci.nsIScriptableInputStream
+  );
 }
 
-
 // PgpWkdHandler implementation
 PgpWkdHandler.prototype = {
-
   data: "",
   mimePartNumber: "",
   uri: null,
   backgroundJob: false,
 
   QueryInterface: EnigmailCompat.generateQI([Ci.nsIStreamListener]),
 
-  onStartRequest: function(request, ctxt) {
+  onStartRequest(request, ctxt) {
     EnigmailLog.DEBUG("wksMimeHandler.jsm: onStartRequest\n"); // always log this one
 
     this.mimeSvc = request.QueryInterface(Ci.nsIPgpMimeProxy);
-    let uri = null;
     if ("messageURI" in this.mimeSvc) {
-      uri = this.mimeSvc.messageURI;
-    }
-    else {
-      uri = ctxt;
+      this.uri = this.mimeSvc.messageURI;
+    } else {
+      this.uri = ctxt;
     }
 
     if ("mimePart" in this.mimeSvc) {
       this.mimePartNumber = this.mimeSvc.mimePart;
-    }
-    else {
+    } else {
       this.mimePartNumber = "";
     }
     this.data = "";
     this.msgWindow = EnigmailVerify.lastMsgWindow;
     this.backgroundJob = false;
 
     if (this.uri) {
-      this.backgroundJob = (this.uri.spec.search(/[&?]header=(print|quotebody|enigmailConvert)/) >= 0);
+      this.backgroundJob =
+        this.uri.spec.search(/[&?]header=(print|quotebody|enigmailConvert)/) >=
+        0;
     }
-
   },
 
-  onDataAvailable: function(req, dummy, stream, offset, count) {
+  onDataAvailable(req, dummy, stream, offset, count) {
     if ("messageURI" in this.mimeSvc) {
       // TB >= 67
       stream = dummy;
       count = offset;
     }
 
     LOCAL_DEBUG("wksMimeHandler.jsm: onDataAvailable: " + count + "\n");
     if (count > 0) {
       this.inStream.init(stream);
       let data = this.inStream.read(count);
       this.data += data;
     }
   },
 
-  onStopRequest: function() {
+  onStopRequest() {
     EnigmailLog.DEBUG("wksMimeHandler.jsm: onStopRequest\n");
 
     if (this.data.search(/-----BEGIN PGP MESSAGE-----/i) >= 0) {
       this.decryptChallengeData();
     }
 
     let jsonStr = this.requestToJsonString(this.data);
     let msg = "";
 
-    if (this.data.search(/^\s*type:\s+confirmation-request/mi) >= 0) {
+    if (this.data.search(/^\s*type:\s+confirmation-request/im) >= 0) {
       msg = EnigmailLocale.getString("wkdMessage.body.req");
-    }
-    else {
+    } else {
       msg = EnigmailLocale.getString("wkdMessage.body.process");
     }
 
     this.returnData(msg);
     this.displayStatus(jsonStr);
   },
 
-  decryptChallengeData: function() {
+  decryptChallengeData() {
     EnigmailLog.DEBUG("wksMimeHandler.jsm: decryptChallengeData()\n");
-    let windowManager = Cc[APPSHELL_MEDIATOR_CONTRACTID].getService(Ci.nsIWindowMediator);
+    let windowManager = Services.wm;
     let win = windowManager.getMostRecentWindow(null);
     let statusFlagsObj = {};
 
-    let res = EnigmailDecryption.decryptMessage(win,
+    let res = EnigmailDecryption.decryptMessage(
+      win,
       0,
-      this.data, {}, {}, statusFlagsObj, {}, {}, {}, {}, {}, {});
+      this.data,
+      {},
+      {},
+      statusFlagsObj,
+      {},
+      {},
+      {},
+      {},
+      {},
+      {}
+    );
 
     if (statusFlagsObj.value & EnigmailConstants.DECRYPTION_OKAY) {
       this.data = res;
     }
-    EnigmailLog.DEBUG("wksMimeHandler.jsm: decryptChallengeData: decryption result: " + res + "\n");
+    EnigmailLog.DEBUG(
+      "wksMimeHandler.jsm: decryptChallengeData: decryption result: " +
+        res +
+        "\n"
+    );
   },
 
   // convert request data into JSON-string and parse it
-  requestToJsonString: function() {
+  requestToJsonString() {
     // convert
     let lines = this.data.split(/\r?\n/);
-    let s = '{';
+    let s = "{";
     for (let l of lines) {
       let m = l.match(/^([^\s:]+)(:\s*)([^\s].+)$/);
       if (m && m.length >= 4) {
         s += '"' + m[1].trim().toLowerCase() + '": "' + m[3].trim() + '",';
       }
     }
 
-    let o = {};
     s = s.substr(0, s.length - 1) + "}";
 
     return s;
   },
 
   // return data to libMime
-  returnData: function(message) {
+  returnData(message) {
     EnigmailLog.DEBUG("wksMimeHandler.jsm: returnData():\n");
 
-    let msg = 'Content-Type: text/plain; charset="utf-8"\r\n' +
-      'Content-Transfer-Encoding: 8bit\r\n\r\n' +
-      message + '\r\n';
+    let msg =
+      'Content-Type: text/plain; charset="utf-8"\r\n' +
+      "Content-Transfer-Encoding: 8bit\r\n\r\n" +
+      message +
+      "\r\n";
 
     if ("outputDecryptedData" in this.mimeSvc) {
       this.mimeSvc.outputDecryptedData(msg, msg.length);
-    }
-    else {
-      let gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
+    } else {
+      let gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
+        Ci.nsIStringInputStream
+      );
       gConv.setData(msg, msg.length);
       try {
         this.mimeSvc.onStartRequest(null);
         this.mimeSvc.onDataAvailable(null, gConv, 0, msg.length);
         this.mimeSvc.onStopRequest(null, 0);
-      }
-      catch (ex) {
-        EnigmailLog.ERROR("wksMimeHandler.jsm: returnData(): mimeSvc.onDataAvailable failed:\n" + ex.toString());
+      } catch (ex) {
+        EnigmailLog.ERROR(
+          "wksMimeHandler.jsm: returnData(): mimeSvc.onDataAvailable failed:\n" +
+            ex.toString()
+        );
       }
     }
   },
 
-  displayStatus: function(jsonStr) {
+  displayStatus(jsonStr) {
     EnigmailLog.DEBUG("wksMimeHandler.jsm: displayStatus\n");
-    if (this.msgWindow === null || this.backgroundJob)
+    if (this.msgWindow === null || this.backgroundJob) {
       return;
+    }
 
     try {
       LOCAL_DEBUG("wksMimeHandler.jsm: displayStatus displaying result\n");
       let headerSink = EnigmailSingletons.messageReader;
 
       if (headerSink) {
-        headerSink.processDecryptionResult(this.uri, "wksConfirmRequest", jsonStr, this.mimePartNumber);
+        headerSink.processDecryptionResult(
+          this.uri,
+          "wksConfirmRequest",
+          jsonStr,
+          this.mimePartNumber
+        );
       }
-
-    }
-    catch (ex) {
+    } catch (ex) {
       EnigmailLog.writeException("wksMimeHandler.jsm", ex);
     }
-  }
+  },
 };
 
-
 ////////////////////////////////////////////////////////////////////
 // General-purpose functions, not exported
 
 function LOCAL_DEBUG(str) {
-  if (gDebugLog) EnigmailLog.DEBUG(str);
+  if (gDebugLog) {
+    EnigmailLog.DEBUG(str);
+  }
 }
 
 function initModule() {
-  var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
+  var env = Cc["@mozilla.org/process/environment;1"].getService(
+    Ci.nsIEnvironment
+  );
   var nspr_log_modules = env.get("NSPR_LOG_MODULES");
   var matches = nspr_log_modules.match(/wksMimeHandler:(\d+)/);
 
-  if (matches && (matches.length > 1)) {
-    if (matches[1] > 2) gDebugLog = true;
+  if (matches && matches.length > 1) {
+    if (matches[1] > 2) {
+      gDebugLog = true;
+    }
   }
 }
 
 initModule();
--- a/mail/extensions/openpgp/content/modules/xhrUtils.jsm
+++ b/mail/extensions/openpgp/content/modules/xhrUtils.jsm
@@ -4,132 +4,133 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
 const EXPORTED_SYMBOLS = ["EnigmailXhrUtils"];
 
 var EnigmailXhrUtils = {
-
   /**
    * Create an error description from an XMLHttpRequest error.
    * Adapted from the patch for mozTCPSocket error reporting (bug 861196).
    *
    * @param xhr: XMLHttpRequest Object
    *
    * @return Object:
    *    - type: String: one of SecurityCertificate, SecurityProtocol, Network
    *    - name: Detailed error text
    */
-  createTCPErrorFromFailedXHR: function(xhr) {
+  createTCPErrorFromFailedXHR(xhr) {
     let status = xhr.channel.QueryInterface(Ci.nsIRequest).status;
 
     let errType;
     let errName;
 
-    if ((status & 0xff0000) === 0x5a0000) { // Security module
+    if ((status & 0xff0000) === 0x5a0000) {
+      // Security module
       const nsINSSErrorsService = Ci.nsINSSErrorsService;
-      let nssErrorsService = Cc['@mozilla.org/nss_errors_service;1'].getService(nsINSSErrorsService);
+      let nssErrorsService = Cc["@mozilla.org/nss_errors_service;1"].getService(
+        nsINSSErrorsService
+      );
       let errorClass;
       // getErrorClass will throw a generic NS_ERROR_FAILURE if the error code is
       // somehow not in the set of covered errors.
       try {
         errorClass = nssErrorsService.getErrorClass(status);
-      }
-      catch (ex) {
-        errorClass = 'SecurityProtocol';
+      } catch (ex) {
+        errorClass = "SecurityProtocol";
       }
       if (errorClass == nsINSSErrorsService.ERROR_CLASS_BAD_CERT) {
-        errType = 'SecurityCertificate';
-      }
-      else {
-        errType = 'SecurityProtocol';
+        errType = "SecurityCertificate";
+      } else {
+        errType = "SecurityProtocol";
       }
 
       // NSS_SEC errors (happen below the base value because of negative vals)
-      if ((status & 0xffff) < Math.abs(nsINSSErrorsService.NSS_SEC_ERROR_BASE)) {
+      if (
+        (status & 0xffff) <
+        Math.abs(nsINSSErrorsService.NSS_SEC_ERROR_BASE)
+      ) {
         // The bases are actually negative, so in our positive numeric space, we
         // need to subtract the base off our value.
-        let nssErr = Math.abs(nsINSSErrorsService.NSS_SEC_ERROR_BASE) -
-          (status & 0xffff);
+        let nssErr =
+          Math.abs(nsINSSErrorsService.NSS_SEC_ERROR_BASE) - (status & 0xffff);
         switch (nssErr) {
           case 11: // SEC_ERROR_EXPIRED_CERTIFICATE, sec(11)
-            errName = 'SecurityExpiredCertificateError';
+            errName = "SecurityExpiredCertificateError";
             break;
           case 12: // SEC_ERROR_REVOKED_CERTIFICATE, sec(12)
-            errName = 'SecurityRevokedCertificateError';
+            errName = "SecurityRevokedCertificateError";
             break;
 
-            // per bsmith, we will be unable to tell these errors apart very soon,
-            // so it makes sense to just folder them all together already.
+          // per bsmith, we will be unable to tell these errors apart very soon,
+          // so it makes sense to just folder them all together already.
           case 13: // SEC_ERROR_UNKNOWN_ISSUER, sec(13)
           case 20: // SEC_ERROR_UNTRUSTED_ISSUER, sec(20)
           case 21: // SEC_ERROR_UNTRUSTED_CERT, sec(21)
           case 36: // SEC_ERROR_CA_CERT_INVALID, sec(36)
-            errName = 'SecurityUntrustedCertificateIssuerError';
+            errName = "SecurityUntrustedCertificateIssuerError";
             break;
           case 90: // SEC_ERROR_INADEQUATE_KEY_USAGE, sec(90)
-            errName = 'SecurityInadequateKeyUsageError';
+            errName = "SecurityInadequateKeyUsageError";
             break;
           case 176: // SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED, sec(176)
-            errName = 'SecurityCertificateSignatureAlgorithmDisabledError';
+            errName = "SecurityCertificateSignatureAlgorithmDisabledError";
             break;
           default:
-            errName = 'SecurityError';
+            errName = "SecurityError";
+            break;
+        }
+      } else {
+        let sslErr =
+          Math.abs(nsINSSErrorsService.NSS_SSL_ERROR_BASE) - (status & 0xffff);
+        switch (sslErr) {
+          case 3: // SSL_ERROR_NO_CERTIFICATE, ssl(3)
+            errName = "SecurityNoCertificateError";
+            break;
+          case 4: // SSL_ERROR_BAD_CERTIFICATE, ssl(4)
+            errName = "SecurityBadCertificateError";
+            break;
+          case 8: // SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE, ssl(8)
+            errName = "SecurityUnsupportedCertificateTypeError";
+            break;
+          case 9: // SSL_ERROR_UNSUPPORTED_VERSION, ssl(9)
+            errName = "SecurityUnsupportedTLSVersionError";
+            break;
+          case 12: // SSL_ERROR_BAD_CERT_DOMAIN, ssl(12)
+            errName = "SecurityCertificateDomainMismatchError";
+            break;
+          default:
+            errName = "SecurityError";
             break;
         }
       }
-      else {
-        let sslErr = Math.abs(nsINSSErrorsService.NSS_SSL_ERROR_BASE) -
-          (status & 0xffff);
-        switch (sslErr) {
-          case 3: // SSL_ERROR_NO_CERTIFICATE, ssl(3)
-            errName = 'SecurityNoCertificateError';
-            break;
-          case 4: // SSL_ERROR_BAD_CERTIFICATE, ssl(4)
-            errName = 'SecurityBadCertificateError';
-            break;
-          case 8: // SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE, ssl(8)
-            errName = 'SecurityUnsupportedCertificateTypeError';
-            break;
-          case 9: // SSL_ERROR_UNSUPPORTED_VERSION, ssl(9)
-            errName = 'SecurityUnsupportedTLSVersionError';
-            break;
-          case 12: // SSL_ERROR_BAD_CERT_DOMAIN, ssl(12)
-            errName = 'SecurityCertificateDomainMismatchError';
-            break;
-          default:
-            errName = 'SecurityError';
-            break;
-        }
-      }
-    }
-    else {
-      errType = 'Network';
+    } else {
+      errType = "Network";
       switch (status) {
         // connect to host:port failed
-        case 0x804B000C: // NS_ERROR_CONNECTION_REFUSED, network(13)
-          errName = 'ConnectionRefusedError';
+        case 0x804b000c: // NS_ERROR_CONNECTION_REFUSED, network(13)
+          errName = "ConnectionRefusedError";
           break;
-          // network timeout error
-        case 0x804B000E: // NS_ERROR_NET_TIMEOUT, network(14)
-          errName = 'NetworkTimeoutError';
+        // network timeout error
+        case 0x804b000e: // NS_ERROR_NET_TIMEOUT, network(14)
+          errName = "NetworkTimeoutError";
           break;
-          // hostname lookup failed
-        case 0x804B001E: // NS_ERROR_UNKNOWN_HOST, network(30)
-          errName = 'DomainNotFoundError';
+        // hostname lookup failed
+        case 0x804b001e: // NS_ERROR_UNKNOWN_HOST, network(30)
+          errName = "DomainNotFoundError";
           break;
-        case 0x804B0047: // NS_ERROR_NET_INTERRUPT, network(71)
-          errName = 'NetworkInterruptError';
+        case 0x804b0047: // NS_ERROR_NET_INTERRUPT, network(71)
+          errName = "NetworkInterruptError";
           break;
         default:
-          errName = 'NetworkError';
+          errName = "NetworkError";
           break;
       }
     }
 
     return {
       name: errName,
-      type: errType
+      type: errType,
     };
-  }
+  },
 };
--- a/mail/extensions/openpgp/content/modules/zbase32.jsm
+++ b/mail/extensions/openpgp/content/modules/zbase32.jsm
@@ -17,62 +17,64 @@ var EnigmailZBase32 = {
 
   /**
    * Encode a string in Z-Base-32 encoding
    *
    * @param str   String - input string
    *
    * @return String - econded string
    */
-  encode: function(str) {
+  encode(str) {
     let a = this.a;
     let pad = this.pad;
     let len = str.length;
     let o = "";
-    let w, c, r = 0,
+    let w,
+      c,
+      r = 0,
       sh = 0;
 
     for (let i = 0; i < len; i += 5) {
       // mask top 5 bits
       c = str.charCodeAt(i);
       w = 0xf8 & c;
       o += a.charAt(w >> 3);
       r = 0x07 & c;
       sh = 2;
 
-      if ((i + 1) < len) {
+      if (i + 1 < len) {
         c = str.charCodeAt(i + 1);
         // mask top 2 bits
         w = 0xc0 & c;
         o += a.charAt((r << 2) + (w >> 6));
         o += a.charAt((0x3e & c) >> 1);
         r = c & 0x01;
         sh = 4;
       }
 
-      if ((i + 2) < len) {
+      if (i + 2 < len) {
         c = str.charCodeAt(i + 2);
         // mask top 4 bits
         w = 0xf0 & c;
         o += a.charAt((r << 4) + (w >> 4));
         r = 0x0f & c;
         sh = 1;
       }
 
-      if ((i + 3) < len) {
+      if (i + 3 < len) {
         c = str.charCodeAt(i + 3);
         // mask top 1 bit
         w = 0x80 & c;
         o += a.charAt((r << 1) + (w >> 7));
         o += a.charAt((0x7c & c) >> 2);
         r = 0x03 & c;
         sh = 3;
       }
 
-      if ((i + 4) < len) {
+      if (i + 4 < len) {
         c = str.charCodeAt(i + 4);
         // mask top 3 bits
         w = 0xe0 & c;
         o += a.charAt((r << 3) + (w >> 5));
         o += a.charAt(0x1f & c);
         r = 0;
         sh = 0;
       }
@@ -87,11 +89,20 @@ var EnigmailZBase32 = {
     if (padlen === 8) {
       return o;
     }
 
     if (padlen === 1 || padlen === 3 || padlen === 4 || padlen === 6) {
       return o + pad.repeat(padlen);
     }
 
-    throw 'there was some kind of error:\npadlen:' + padlen + ' ,r:' + r + ' ,sh:' + sh + ', w:' + w;
-  }
+    throw new Error(
+      "there was some kind of error:\npadlen:" +
+        padlen +
+        " ,r:" +
+        r +
+        " ,sh:" +
+        sh +
+        ", w:" +
+        w
+    );
+  },
 };
--- a/mail/extensions/openpgp/content/strings/enigmail.properties
+++ b/mail/extensions/openpgp/content/strings/enigmail.properties
@@ -383,17 +383,16 @@ sendLaterCmd.label=Send Later
 # Strings used in enigmailAttachmentDialog.js
 pgpMimeNote=NOTE: PGP/MIME is not supported by all email clients. If you are unsure, select the %S option.
 first=first
 second=second
 
 # Strings used in am-enigprefs.js / enigmailEditIdentity.js
 encryptKeyHeader=Select OpenPGP Key for Encryption
 identityName=Identity: %S
-amPrefAutocrypt.desc=<html:span class='enigmailLink' href='https://autocrypt.org'>Autocrypt</html:span> is a standard that defines how to achieve convenient end-to-end-encryption of e-mails. It specifies how e-mail programs negotiate encryption capabilities using regular e-mails.
 
 
 # Strings used in enigmailSingleRcptSettings.js
 noEncryption=You have activated encryption, but you did not select a key. In order to encrypt emails sent to %1$S, you need to specify one or several valid key(s) from your key list. Do you want to disable encryption for %2$S?
 noKeyToUse=(none - no encryption)
 noEmptyRule=The Rule may not be empty! Please set an email address in the Rule field.
 invalidAddress=The email address(es) you have entered are not valid. You should not set the names of the recipients, just the email addresses. E.g.:\nInvalid: Some Name <some.name@address.net>\nValid:   some.name@address.net
 noCurlyBrackets=The curly brackets {} have a special meaning and should not be used in an email address. If you want to modify the matching behavior for this rule, use the 'Apply rule if recipient ...' option.\nMore information is available from the Help button.
--- a/mail/extensions/openpgp/content/ui/am-enigprefs.js
+++ b/mail/extensions/openpgp/content/ui/am-enigprefs.js
@@ -1,20 +1,25 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
-var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-var EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
+var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm")
+  .EnigmailLog;
+var EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
 
-if (!Enigmail) var Enigmail = {};
+if (!Enigmail) {
+  var Enigmail = {};
+}
 
 var gPref = null;
 
 function onInit() {
   EnigmailLog.DEBUG("am-enigprefs.js: onInit()\n");
 
   try {
     performInit();
@@ -69,14 +74,13 @@ function disableIfLocked(prefstrArray) {
 function enigmailOnAcceptEditor() {
   EnigmailLog.DEBUG("am-enigprefs.js: enigmailOnAcceptEditor()\n");
 
   Enigmail.edit.onSave();
 
   return true; // allow to close dialog in all cases
 }
 
-
 function saveChanges() {}
 
 document.addEventListener("dialogaccept", function(event) {
   Enigmail.edit.onAcceptEditor();
 });
--- a/mail/extensions/openpgp/content/ui/commonWorkflows.js
+++ b/mail/extensions/openpgp/content/ui/commonWorkflows.js
@@ -1,64 +1,88 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-var EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm")
+  .EnigmailKey;
+var EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
 
 /**
  * import OpenPGP keys from file
  */
-function EnigmailCommon_importKeysFromFile()  {
-
-  let inFile = EnigmailDialog.filePicker(window, EnigmailLocale.getString("importKeyFile"),
-    "", false, "*.asc", "", [EnigmailLocale.getString("gnupgFile"), "*.asc;*.gpg;*.pgp"]);
-  if (!inFile) return false;
+function EnigmailCommon_importKeysFromFile() {
+  let inFile = EnigmailDialog.filePicker(
+    window,
+    EnigmailLocale.getString("importKeyFile"),
+    "",
+    false,
+    "*.asc",
+    "",
+    [EnigmailLocale.getString("gnupgFile"), "*.asc;*.gpg;*.pgp"]
+  );
+  if (!inFile) {
+    return false;
+  }
 
   let errorMsgObj = {};
   // preview
   let preview = EnigmailKey.getKeyListFromKeyFile(inFile, errorMsgObj);
 
   if (errorMsgObj.value && errorMsgObj.value.length > 0) {
     EnigmailDialog.alert(window, errorMsgObj.value);
     return false;
   }
   let exitStatus = -1;
 
   if (preview.length > 0) {
     if (preview.length == 1) {
-      exitStatus = EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("doImportOne", [preview[0].name, preview[0].id]));
-    }
-    else {
-      exitStatus = EnigmailDialog.confirmDlg(window,
+      exitStatus = EnigmailDialog.confirmDlg(
+        window,
+        EnigmailLocale.getString("doImportOne", [
+          preview[0].name,
+          preview[0].id,
+        ])
+      );
+    } else {
+      exitStatus = EnigmailDialog.confirmDlg(
+        window,
         EnigmailLocale.getString("doImportMultiple", [
-          preview.map(function(a) {
-            return "\t" + a.name + " (" + a.id + ")";
-          }).join("\n")
-        ]));
+          preview
+            .map(function(a) {
+              return "\t" + a.name + " (" + a.id + ")";
+            })
+            .join("\n"),
+        ])
+      );
     }
 
     if (exitStatus) {
       // import
       let exitCode = EnigmailKeyRing.importKeyFromFile(inFile, errorMsgObj);
       if (exitCode !== 0) {
-        EnigmailDialog.alert(window, EnigmailLocale.getString("importKeysFailed") + "\n\n" + errorMsgObj.value);
-      }
-      else {
+        EnigmailDialog.alert(
+          window,
+          EnigmailLocale.getString("importKeysFailed") +
+            "\n\n" +
+            errorMsgObj.value
+        );
+      } else {
         var keyList = preview.map(function(a) {
           return a.id;
         });
         EnigmailDialog.keyImportDlg(window, keyList);
         return true;
       }
     }
   }
--- a/mail/extensions/openpgp/content/ui/enigmailCommon.js
+++ b/mail/extensions/openpgp/content/ui/enigmailCommon.js
@@ -1,234 +1,278 @@
-/*global EnigmailFiles: false, EnigmailCore: false, EnigmailApp: false, EnigmailDialog: false, EnigmailWindows: false, EnigmailTime: false */
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 /**
  * PLEASE NOTE: this module is legacy and must not be used for newe code - it will be removed!
  */
 
-
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 // enigmailCommon.js: shared JS functions for Enigmail
 
 // WARNING: This module functions must not be loaded in overlays to standard functionality!
 
 // Many of these components are not used in this file, but are instead used in other files that are loaded together with EnigmailCommon
-var EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-var EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-var EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-var EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-var EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-var EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-var EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-var EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-var EnigmailTrust = ChromeUtils.import("chrome://openpgp/content/modules/trust.jsm").EnigmailTrust;
-var EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-var EnigmailErrorHandling = ChromeUtils.import("chrome://openpgp/content/modules/errorHandling.jsm").EnigmailErrorHandling;
-var EnigmailKeyServer = ChromeUtils.import("chrome://openpgp/content/modules/keyserver.jsm").EnigmailKeyServer;
-var EnigmailEvents = ChromeUtils.import("chrome://openpgp/content/modules/events.jsm").EnigmailEvents;
-var EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-var EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-var EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+var EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm")
+  .EnigmailKey;
+var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm")
+  .EnigmailLog;
+var EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+var EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+var EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm")
+  .EnigmailApp;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+var EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+var EnigmailTime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/time.jsm"
+).EnigmailTime;
+var EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+var EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+var EnigmailTrust = ChromeUtils.import(
+  "chrome://openpgp/content/modules/trust.jsm"
+).EnigmailTrust;
+var EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+var EnigmailErrorHandling = ChromeUtils.import(
+  "chrome://openpgp/content/modules/errorHandling.jsm"
+).EnigmailErrorHandling;
+var EnigmailKeyServer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyserver.jsm"
+).EnigmailKeyServer;
+var EnigmailEvents = ChromeUtils.import(
+  "chrome://openpgp/content/modules/events.jsm"
+).EnigmailEvents;
+var EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm")
+  .EnigmailGpg;
+var EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+var EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
-var OpenPGPMasterpass = ChromeUtils.import("chrome://openpgp/content/modules/masterpass.jsm").OpenPGPMasterpass;
+var OpenPGPMasterpass = ChromeUtils.import(
+  "chrome://openpgp/content/modules/masterpass.jsm"
+).OpenPGPMasterpass;
 var RNP = ChromeUtils.import("chrome://openpgp/content/modules/rnp.jsm").RNP;
 
-
 // The compatible Enigmime version
 var gEnigmailSvc;
 var gEnigPromptSvc;
 
-
 // Maximum size of message directly processed by Enigmail
 const ENIG_PROCESSINFO_CONTRACTID = "@mozilla.org/xpcom/process-info;1";
 const ENIG_ENIGMAIL_CONTRACTID = "@mozdev.org/enigmail/enigmail;1";
 const ENIG_STRINGBUNDLE_CONTRACTID = "@mozilla.org/intl/stringbundle;1";
 const ENIG_LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";
 const ENIG_DIRSERVICE_CONTRACTID = "@mozilla.org/file/directory_service;1";
 const ENIG_MIME_CONTRACTID = "@mozilla.org/mime;1";
-const ENIG_WMEDIATOR_CONTRACTID = "@mozilla.org/rdf/datasource;1?name=window-mediator";
+const ENIG_WMEDIATOR_CONTRACTID =
+  "@mozilla.org/rdf/datasource;1?name=window-mediator";
 const ENIG_ASS_CONTRACTID = "@mozilla.org/appshell/appShellService;1";
 const ENIG_LOCALE_SVC_CONTRACTID = "@mozilla.org/intl/nslocaleservice;1";
 const ENIG_DATE_FORMAT_CONTRACTID = "@mozilla.org/intl/scriptabledateformat;1";
-const ENIG_ACCOUNT_MANAGER_CONTRACTID = "@mozilla.org/messenger/account-manager;1";
+const ENIG_ACCOUNT_MANAGER_CONTRACTID =
+  "@mozilla.org/messenger/account-manager;1";
 const ENIG_THREAD_MANAGER_CID = "@mozilla.org/thread-manager;1";
 const ENIG_SIMPLEURI_CONTRACTID = "@mozilla.org/network/simple-uri;1";
 
-
 const ENIG_STANDARD_URL_CONTRACTID = "@mozilla.org/network/standard-url;1";
-const ENIG_SCRIPTABLEINPUTSTREAM_CONTRACTID = "@mozilla.org/scriptableinputstream;1";
+const ENIG_SCRIPTABLEINPUTSTREAM_CONTRACTID =
+  "@mozilla.org/scriptableinputstream;1";
 const ENIG_BINARYINPUTSTREAM_CONTRACTID = "@mozilla.org/binaryinputstream;1";
 const ENIG_SAVEASCHARSET_CONTRACTID = "@mozilla.org/intl/saveascharset;1";
 
 const ENIG_STREAMCONVERTERSERVICE_CID_STR =
   "{892FFEB0-3F80-11d3-A16C-0050041CAF44}";
 
-
-const ENIG_ISCRIPTABLEUNICODECONVERTER_CONTRACTID = "@mozilla.org/intl/scriptableunicodeconverter";
+const ENIG_ISCRIPTABLEUNICODECONVERTER_CONTRACTID =
+  "@mozilla.org/intl/scriptableunicodeconverter";
 
 const ENIG_IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
 
-const ENIG_C = Components.classes;
-const ENIG_I = Components.interfaces;
-
-
 // field ID's of key list (as described in the doc/DETAILS file in the GnuPG distribution)
 const ENIG_KEY_TRUST = 1;
 const ENIG_KEY_ID = 4;
 const ENIG_CREATED = 5;
 const ENIG_EXPIRY = 6;
 const ENIG_UID_ID = 7;
 const ENIG_OWNERTRUST = 8;
 const ENIG_USER_ID = 9;
 const ENIG_SIG_TYPE = 10;
 const ENIG_KEY_USE_FOR = 11;
 
 const ENIG_KEY_EXPIRED = "e";
 const ENIG_KEY_REVOKED = "r";
 const ENIG_KEY_INVALID = "i";
 const ENIG_KEY_DISABLED = "d";
-const ENIG_KEY_NOT_VALID = ENIG_KEY_EXPIRED + ENIG_KEY_REVOKED + ENIG_KEY_INVALID + ENIG_KEY_DISABLED;
-
+const ENIG_KEY_NOT_VALID =
+  ENIG_KEY_EXPIRED + ENIG_KEY_REVOKED + ENIG_KEY_INVALID + ENIG_KEY_DISABLED;
 
 // GUI List: The corresponding image to set the "active" flag / checkbox
 const ENIG_IMG_NOT_SELECTED = "chrome://openpgp/content/ui/check0.png";
 const ENIG_IMG_SELECTED = "chrome://openpgp/content/ui/check1.png";
 const ENIG_IMG_DISABLED = "chrome://openpgp/content/ui/check2.png";
 
-
-// Encryption flags
-if (EnigmailConstants) {
-  const ENIG_SIGN = EnigmailConstants.SEND_SIGNED;
-  const ENIG_ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
-  const ENIG_ENCRYPT_OR_SIGN = ENIG_ENCRYPT | ENIG_SIGN;
-}
-
 // UsePGPMimeOption values
 const PGP_MIME_NEVER = 0;
 const PGP_MIME_POSSIBLE = 1;
 const PGP_MIME_ALWAYS = 2;
 
 const ENIG_POSSIBLE_PGPMIME = EnigmailConstants.POSSIBLE_PGPMIME;
 const ENIG_PGP_DESKTOP_ATT = -2082;
 
-var gUsePGPMimeOptionList = ["usePGPMimeNever",
+var gUsePGPMimeOptionList = [
+  "usePGPMimeNever",
   "usePGPMimePossible",
-  "usePGPMimeAlways"
+  "usePGPMimeAlways",
 ];
 
 // sending options:
-var gEnigEncryptionModel = ["encryptionModelConvenient",
-  "encryptionModelManually"
+var gEnigEncryptionModel = [
+  "encryptionModelConvenient",
+  "encryptionModelManually",
 ];
-var gEnigAcceptedKeys = ["acceptedKeysValid",
-  "acceptedKeysAll"
+var gEnigAcceptedKeys = ["acceptedKeysValid", "acceptedKeysAll"];
+var gEnigAutoSendEncrypted = [
+  "autoSendEncryptedNever",
+  "autoSendEncryptedIfKeys",
 ];
-var gEnigAutoSendEncrypted = ["autoSendEncryptedNever",
-  "autoSendEncryptedIfKeys"
-];
-var gEnigConfirmBeforeSending = ["confirmBeforeSendingNever",
+var gEnigConfirmBeforeSending = [
+  "confirmBeforeSendingNever",
   "confirmBeforeSendingAlways",
   "confirmBeforeSendingIfEncrypted",
   "confirmBeforeSendingIfNotEncrypted",
-  "confirmBeforeSendingIfRules"
+  "confirmBeforeSendingIfRules",
 ];
 
 const ENIG_BUTTON_POS_0 = 1;
 const ENIG_BUTTON_POS_1 = 1 << 8;
 const ENIG_BUTTON_POS_2 = 1 << 16;
 const ENIG_BUTTON_TITLE_IS_STRING = 127;
 
 const ENIG_HEADERMODE_KEYID = 0x01;
 const ENIG_HEADERMODE_URL = 0x10;
 
-
-
 function EnigGetFrame(win, frameName) {
   return EnigmailWindows.getFrame(win, frameName);
 }
 
 // Initializes enigmailCommon
 function EnigInitCommon(id) {
   EnigmailLog.DEBUG("enigmailCommon.js: EnigInitCommon: id=" + id + "\n");
 
-  gEnigPromptSvc = enigGetService("@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService");
+  gEnigPromptSvc = enigGetService(
+    "@mozilla.org/embedcomp/prompt-service;1",
+    "nsIPromptService"
+  );
 }
 
-
 function GetEnigmailSvc() {
-  if (!gEnigmailSvc)
+  if (!gEnigmailSvc) {
     gEnigmailSvc = EnigmailCore.getService(window);
+  }
   return gEnigmailSvc;
 }
 
 // maxBytes == -1 => read everything
 function EnigReadURLContents(url, maxBytes) {
-  EnigmailLog.DEBUG("enigmailCommon.js: EnigReadURLContents: url=" + url +
-    ", " + maxBytes + "\n");
+  EnigmailLog.DEBUG(
+    "enigmailCommon.js: EnigReadURLContents: url=" +
+      url +
+      ", " +
+      maxBytes +
+      "\n"
+  );
 
   var ioServ = enigGetService(ENIG_IOSERVICE_CONTRACTID, "nsIIOService");
-  if (!ioServ)
-    throw Components.results.NS_ERROR_FAILURE;
+  if (!ioServ) {
+    throw Cr.NS_ERROR_FAILURE;
+  }
 
   var fileChannel = EnigmailStreams.createChannel(url);
 
   var rawInStream = fileChannel.open();
 
-  var inStream = ENIG_C[ENIG_BINARYINPUTSTREAM_CONTRACTID].createInstance(ENIG_I.nsIBinaryInputStream);
+  var inStream = Cc[ENIG_BINARYINPUTSTREAM_CONTRACTID].createInstance(
+    Ci.nsIBinaryInputStream
+  );
   inStream.setInputStream(rawInStream);
 
   var available = inStream.available();
-  if ((maxBytes < 0) || (maxBytes > available))
+  if (maxBytes < 0 || maxBytes > available) {
     maxBytes = available;
+  }
 
   var data = inStream.readBytes(maxBytes);
 
   inStream.close();
 
   return data;
 }
 
 // maxBytes == -1 => read whole file
 function EnigReadFileContents(localFile, maxBytes) {
+  EnigmailLog.DEBUG(
+    "enigmailCommon.js: EnigReadFileContents: file=" +
+      localFile.leafName +
+      ", " +
+      maxBytes +
+      "\n"
+  );
 
-  EnigmailLog.DEBUG("enigmailCommon.js: EnigReadFileContents: file=" + localFile.leafName +
-    ", " + maxBytes + "\n");
-
-  if (!localFile.exists() || !localFile.isReadable())
-    throw Components.results.NS_ERROR_FAILURE;
+  if (!localFile.exists() || !localFile.isReadable()) {
+    throw Cr.NS_ERROR_FAILURE;
+  }
 
   var ioServ = enigGetService(ENIG_IOSERVICE_CONTRACTID, "nsIIOService");
-  if (!ioServ)
-    throw Components.results.NS_ERROR_FAILURE;
+  if (!ioServ) {
+    throw Cr.NS_ERROR_FAILURE;
+  }
 
   var fileURI = ioServ.newFileURI(localFile);
   return EnigReadURLContents(fileURI.asciiSpec, maxBytes);
-
 }
 
 ///////////////////////////////////////////////////////////////////////////////
 
-
 // write exception information
 function EnigWriteException(referenceInfo, ex) {
   EnigmailLog.writeException(referenceInfo, ex);
 }
 
 ///////////////////////////////////////////////////////////////////////////////
 
 function EnigAlert(mesg) {
@@ -240,45 +284,64 @@ function EnigAlert(mesg) {
  * checkBoxLabel: if not null, display checkbox with text; the checkbox state is returned in checkedObj
  * button-Labels: use "&" to indicate access key
  *     use "buttonType:label" or ":buttonType" to indicate special button types
  *        (buttonType is one of cancel, help, extra1, extra2)
  * return: 0-2: button Number pressed
  *          -1: ESC or close window button pressed
  *
  */
-function EnigLongAlert(mesg, checkBoxLabel, okLabel, labelButton2, labelButton3, checkedObj) {
-  return EnigmailDialog.longAlert(window, mesg, checkBoxLabel, okLabel, labelButton2, labelButton3, checkedObj);
+function EnigLongAlert(
+  mesg,
+  checkBoxLabel,
+  okLabel,
+  labelButton2,
+  labelButton3,
+  checkedObj
+) {
+  return EnigmailDialog.longAlert(
+    window,
+    mesg,
+    checkBoxLabel,
+    okLabel,
+    labelButton2,
+    labelButton3,
+    checkedObj
+  );
 }
 
 function EnigAlertPref(mesg, prefText) {
   return EnigmailDialog.alertPref(window, mesg, prefText);
 }
 
 // Confirmation dialog with OK / Cancel buttons (both customizable)
 function EnigConfirm(mesg, okLabel, cancelLabel) {
   return EnigmailDialog.confirmDlg(window, mesg, okLabel, cancelLabel);
 }
 
-
 function EnigError(mesg) {
   return gEnigPromptSvc.alert(window, EnigGetString("enigError"), mesg);
 }
 
-
 function EnigHelpWindow(source) {
   EnigmailWindows.openHelpWindow(source);
 }
 
+function EnigDisplayRadioPref(prefName, prefValue, optionElementIds) {
+  EnigmailLog.DEBUG(
+    "enigmailCommon.js: EnigDisplayRadioPref: " +
+      prefName +
+      ", " +
+      prefValue +
+      "\n"
+  );
 
-function EnigDisplayRadioPref(prefName, prefValue, optionElementIds) {
-  EnigmailLog.DEBUG("enigmailCommon.js: EnigDisplayRadioPref: " + prefName + ", " + prefValue + "\n");
-
-  if (prefValue >= optionElementIds.length)
+  if (prefValue >= optionElementIds.length) {
     return;
+  }
 
   var groupElement = document.getElementById("enigmail_" + prefName);
   var optionElement = document.getElementById(optionElementIds[prefValue]);
 
   if (groupElement && optionElement) {
     groupElement.selectedItem = optionElement;
     groupElement.value = prefValue;
   }
@@ -304,87 +367,102 @@ function EnigSavePrefs() {
   return EnigmailPrefs.savePrefs();
 }
 
 function EnigGetPref(prefName) {
   return EnigmailPrefs.getPref(prefName);
 }
 
 function EnigGetDefaultPref(prefName) {
-  EnigmailLog.DEBUG("enigmailCommon.js: EnigGetDefaultPref: prefName=" + prefName + "\n");
+  EnigmailLog.DEBUG(
+    "enigmailCommon.js: EnigGetDefaultPref: prefName=" + prefName + "\n"
+  );
   var prefValue = null;
   try {
     EnigmailPrefs.getPrefBranch().lockPref(prefName);
     prefValue = EnigGetPref(prefName);
     EnigmailPrefs.getPrefBranch().unlockPref(prefName);
   } catch (ex) {}
 
   return prefValue;
 }
 
 function EnigSetPref(prefName, value) {
   return EnigmailPrefs.setPref(prefName, value);
 }
 
-
 function EnigConvertFromUnicode(text, charset) {
-  EnigmailLog.DEBUG("enigmailCommon.js: EnigConvertFromUnicode: " + charset + "\n");
+  EnigmailLog.DEBUG(
+    "enigmailCommon.js: EnigConvertFromUnicode: " + charset + "\n"
+  );
 
-  if (!text)
+  if (!text) {
     return "";
+  }
 
-  if (!charset) charset = "utf-8";
+  if (!charset) {
+    charset = "utf-8";
+  }
 
   // Encode plaintext
   try {
-    var unicodeConv = ENIG_C[ENIG_ISCRIPTABLEUNICODECONVERTER_CONTRACTID].getService(ENIG_I.nsIScriptableUnicodeConverter);
+    var unicodeConv = Cc[
+      ENIG_ISCRIPTABLEUNICODECONVERTER_CONTRACTID
+    ].getService(Ci.nsIScriptableUnicodeConverter);
 
     unicodeConv.charset = charset;
     return unicodeConv.ConvertFromUnicode(text);
-
   } catch (ex) {
-    EnigmailLog.DEBUG("enigmailCommon.js: EnigConvertFromUnicode: caught an exception\n");
+    EnigmailLog.DEBUG(
+      "enigmailCommon.js: EnigConvertFromUnicode: caught an exception\n"
+    );
 
     return text;
   }
 }
 
-
 function EnigConvertToUnicode(text, charset) {
   // EnigmailLog.DEBUG("enigmailCommon.js: EnigConvertToUnicode: "+charset+"\n");
 
-  if (!text || !charset /*|| (charset.toLowerCase() == "iso-8859-1")*/ )
+  if (!text || !charset /*|| (charset.toLowerCase() == "iso-8859-1")*/) {
     return text;
+  }
 
   // Encode plaintext
   try {
-    var unicodeConv = ENIG_C[ENIG_ISCRIPTABLEUNICODECONVERTER_CONTRACTID].getService(ENIG_I.nsIScriptableUnicodeConverter);
+    var unicodeConv = Cc[
+      ENIG_ISCRIPTABLEUNICODECONVERTER_CONTRACTID
+    ].getService(Ci.nsIScriptableUnicodeConverter);
 
     unicodeConv.charset = charset;
     return unicodeConv.ConvertToUnicode(text);
-
   } catch (ex) {
-    EnigmailLog.DEBUG("enigmailCommon.js: EnigConvertToUnicode: caught an exception while converting'" + text + "' to " + charset + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailCommon.js: EnigConvertToUnicode: caught an exception while converting'" +
+        text +
+        "' to " +
+        charset +
+        "\n"
+    );
     return text;
   }
 }
 
 function EnigConvertGpgToUnicode(text) {
   return EnigmailData.convertGpgToUnicode(text);
 }
 
 function EnigFormatFpr(fingerprint) {
   return EnigmailKey.formatFpr(fingerprint);
 }
 
 /////////////////////////
 // Console stuff
 /////////////////////////
 
-
 // return the options passed to a window
 function EnigGetWindowOptions() {
   var winOptions = [];
   if (window.location.search) {
     var optList = window.location.search.substr(1).split(/&/);
     for (var i = 0; i < optList.length; i++) {
       var anOption = optList[i].split(new RegExp("="));
       winOptions[anOption[0]] = unescape(anOption[1]);
@@ -405,41 +483,55 @@ function EnigKeygen() {
   EnigmailWindows.openKeyGen();
 }
 
 // retrieves a localized string from the enigmail.properties stringbundle
 function EnigGetString(aStr) {
   var argList = [];
   // unfortunately arguments.shift() doesn't work, so we use a workaround
 
-  if (arguments.length > 1)
+  if (arguments.length > 1) {
     for (var i = 1; i < arguments.length; i++) {
       argList.push(arguments[i]);
     }
-  return EnigmailLocale.getString(aStr, (arguments.length > 1 ? argList : null));
+  }
+  return EnigmailLocale.getString(aStr, arguments.length > 1 ? argList : null);
 }
 
-
 //get path for temporary directory (e.g. /tmp, C:\TEMP)
 function EnigGetTempDir() {
   return EnigmailFiles.getTempDir();
 }
 
 // get the OS platform
 function EnigGetOS() {
   return EnigmailOS.getOS();
 }
 
 function EnigGetVersion() {
   return EnigmailApp.getVersion();
 }
 
-function EnigFilePicker(title, displayDir, save, defaultExtension, defaultName, filterPairs) {
-  return EnigmailDialog.filePicker(window, title, displayDir, save, defaultExtension,
-    defaultName, filterPairs);
+function EnigFilePicker(
+  title,
+  displayDir,
+  save,
+  defaultExtension,
+  defaultName,
+  filterPairs
+) {
+  return EnigmailDialog.filePicker(
+    window,
+    title,
+    displayDir,
+    save,
+    defaultExtension,
+    defaultName,
+    filterPairs
+  );
 }
 
 // get keys from keyserver
 function EnigDownloadKeys(inputObj, resultObj) {
   return EnigmailWindows.downloadKeys(window, inputObj, resultObj);
 }
 
 // create new PGP Rule
@@ -450,65 +542,62 @@ function EnigNewRule(emailAddress) {
 function EnigGetTrustCode(keyObj) {
   return EnigmailTrust.getTrustCode(keyObj);
 }
 
 function EnigEditKeyTrust(userIdArr, keyIdArr) {
   return EnigmailWindows.editKeyTrust(window, userIdArr, keyIdArr);
 }
 
-
 function EnigEditKeyExpiry(userIdArr, keyIdArr) {
   return EnigmailWindows.editKeyExpiry(window, userIdArr, keyIdArr);
 }
 
 function EnigDisplayKeyDetails(keyId, refresh) {
   return EnigmailWindows.openKeyDetails(window, keyId, refresh);
 }
 
 function EnigSignKey(userId, keyId) {
   return EnigmailWindows.signKey(window, userId, keyId);
 }
 
-
 function EnigChangeKeyPwd(keyId, userId) {
   throw new Error("Not implemented");
 }
 
-
 function EnigRevokeKey(keyId, userId, callbackFunc) {
   throw new Error("Not implemented");
 
   /*
   var enigmailSvc = GetEnigmailSvc();
   if (!enigmailSvc)
     return false;
 
   var userDesc = "0x" + keyId + " - " + userId;
   if (!EnigConfirm(EnigGetString("revokeKeyQuestion", userDesc), EnigGetString("keyMan.button.revokeKey")))
     return false;
 
   var tmpDir = EnigGetTempDir();
   var revFile;
   try {
-    revFile = ENIG_C[ENIG_LOCAL_FILE_CONTRACTID].createInstance(EnigGetLocalFileApi());
+    revFile = Cc[ENIG_LOCAL_FILE_CONTRACTID].createInstance(EnigGetLocalFileApi());
     revFile.initWithPath(tmpDir);
     if (!(revFile.isDirectory() && revFile.isWritable())) {
       EnigAlert(EnigGetString("noTempDir"));
       return false;
     }
   } catch (ex) {}
   revFile.append("revkey.asc");
 
   return true;
   */
 }
 
 function EnigGetLocalFileApi() {
-  return Components.interfaces.nsIFile;
+  return Ci.nsIFile;
 }
 
 function EnigShowPhoto(keyId, userId, photoNumber) {
   EnigmailWindows.showPhoto(window, keyId, userId, photoNumber);
 }
 
 function EnigGetFilePath(nsFileObj) {
   return EnigmailFiles.getFilePath(nsFileObj);
@@ -528,121 +617,132 @@ function EnigCreateRevokeCert(keyId, use
   var enigmailSvc = GetEnigmailSvc();
   if (!enigmailSvc)
     return -1;
 
   return 0;
   */
 }
 
-
 // return the label of trust for a given trust code
 function EnigGetTrustLabel(trustCode) {
   return EnigmailTrust.getTrustLabel(trustCode);
 }
 
 function EnigGetDateTime(dateNum, withDate, withTime) {
   return EnigmailTime.getDateTime(dateNum, withDate, withTime);
 }
 
 function enigCreateInstance(aURL, aInterface) {
-  return ENIG_C[aURL].createInstance(ENIG_I[aInterface]);
+  return Cc[aURL].createInstance(Ci[aInterface]);
 }
 
 function enigGetService(aURL, aInterface) {
   // determine how 'aInterface' is passed and handle accordingly
-  switch (typeof(aInterface)) {
+  switch (typeof aInterface) {
     case "object":
-      return ENIG_C[aURL].getService(aInterface);
+      return Cc[aURL].getService(aInterface);
     case "string":
-      return ENIG_C[aURL].getService(ENIG_I[aInterface]);
+      return Cc[aURL].getService(Ci[aInterface]);
     default:
-      return ENIG_C[aURL].getService();
+      return Cc[aURL].getService();
   }
 }
 
 function EnigCollapseAdvanced(obj, attribute, dummy) {
   return EnigmailFuncs.collapseAdvanced(obj, attribute, dummy);
 }
 
 /**
  * EnigOpenUrlExternally
  *
  * forces a uri to be loaded in an external browser
  *
  * @uri nsIUri object
  */
 function EnigOpenUrlExternally(uri) {
-  let eps = ENIG_C["@mozilla.org/uriloader/external-protocol-service;1"].
-  getService(ENIG_I.nsIExternalProtocolService);
+  let eps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].getService(
+    Ci.nsIExternalProtocolService
+  );
 
   eps.loadURI(uri, null);
 }
 
 function EnigOpenURL(event, hrefObj) {
   try {
-    var ioservice = ENIG_C["@mozilla.org/network/io-service;1"].
-    getService(ENIG_I.nsIIOService);
-    var iUri = ioservice.newURI(hrefObj.href, null, null);
+    var ioservice = Services.io;
+    var iUri = ioservice.newURI(hrefObj.href);
 
     EnigOpenUrlExternally(iUri);
     event.preventDefault();
     event.stopPropagation();
   } catch (ex) {}
 }
 
 function EnigGetHttpUri(aEvent) {
-
   function hRefForClickEvent(aEvent, aDontCheckInputElement) {
     var href;
-    var isKeyCommand = (aEvent.type == "command");
-    var target =
-      isKeyCommand ? document.commandDispatcher.focusedElement : aEvent.target;
+    var isKeyCommand = aEvent.type == "command";
+    var target = isKeyCommand
+      ? document.commandDispatcher.focusedElement
+      : aEvent.target;
 
-    if (target instanceof HTMLAnchorElement ||
+    if (
+      target instanceof HTMLAnchorElement ||
       target instanceof HTMLAreaElement ||
-      target instanceof HTMLLinkElement) {
-      if (target.hasAttribute("href"))
+      target instanceof HTMLLinkElement
+    ) {
+      if (target.hasAttribute("href")) {
         href = target.href;
+      }
     } else if (!aDontCheckInputElement && target instanceof HTMLInputElement) {
-      if (target.form && target.form.action)
+      if (target.form && target.form.action) {
         href = target.form.action;
+      }
     } else {
       // we may be nested inside of a link node
       var linkNode = aEvent.originalTarget;
-      while (linkNode && !(linkNode instanceof HTMLAnchorElement))
+      while (linkNode && !(linkNode instanceof HTMLAnchorElement)) {
         linkNode = linkNode.parentNode;
+      }
 
-      if (linkNode)
+      if (linkNode) {
         href = linkNode.href;
+      }
     }
 
     return href;
   }
 
   // getHttpUri main function
 
   let href = hRefForClickEvent(aEvent);
-  if (!href) return null;
+  if (!href) {
+    return null;
+  }
 
-  EnigmailLog.DEBUG("enigmailAbout.js: interpretHtmlClick: href='" + href + "'\n");
+  EnigmailLog.DEBUG(
+    "enigmailAbout.js: interpretHtmlClick: href='" + href + "'\n"
+  );
 
-  var ioServ = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
-  var uri = ioServ.newURI(href, null, null);
+  var ioServ = Services.io;
+  var uri = ioServ.newURI(href);
 
-  if (Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
-    .getService(Components.interfaces.nsIExternalProtocolService)
-    .isExposedProtocol(uri.scheme) &&
-    (uri.schemeIs("http") || uri.schemeIs("https")))
+  if (
+    Cc["@mozilla.org/uriloader/external-protocol-service;1"]
+      .getService(Ci.nsIExternalProtocolService)
+      .isExposedProtocol(uri.scheme) &&
+    (uri.schemeIs("http") || uri.schemeIs("https"))
+  ) {
     return uri;
+  }
 
   return null;
 }
 
-
 /**
  * GUI List: Set the "active" flag and the corresponding image
  */
 function EnigSetActive(element, status) {
   if (status >= 0) {
     element.setAttribute("active", status.toString());
   }
 
@@ -656,42 +756,40 @@ function EnigSetActive(element, status) 
     case 2:
       element.setAttribute("src", ENIG_IMG_DISABLED);
       break;
     default:
       element.setAttribute("active", -1);
   }
 }
 
-
 /**
  * Receive a GUI List and remove all entries
  *
  * @param  XML-DOM  (it will be changed!)
  */
 function EnigCleanGuiList(guiList) {
   while (guiList.firstChild) {
-    guiList.removeChild(guiList.firstChild);
+    guiList.firstChild.remove();
   }
 }
 
 /**
  * create a new treecell element
  *
  * @param String label of the cell
  *
  * @return treecell node
  */
 function createCell(label) {
   var cell = document.createXULElement("treecell");
   cell.setAttribute("label", label);
   return cell;
 }
 
-
 /**
  * Process the output of GPG and return the key details
  *
  * @param   String  Values separated by colons and linebreaks
  *
  * @return  Object with the following keys:
  *    gUserId: Main user ID
  *    calcTrust,
@@ -714,17 +812,17 @@ function EnigGetKeyDetails(sigListStr) {
 
   var sigList = sigListStr.split(/[\n\r]+/);
   for (var i = 0; i < sigList.length; i++) {
     var aLine = sigList[i].split(/:/);
     switch (aLine[0]) {
       case "pub":
         gUserId = EnigConvertGpgToUnicode(aLine[9]);
         calcTrust = aLine[1];
-        if (aLine[11].indexOf("D") >= 0) {
+        if (aLine[11].includes("D")) {
           calcTrust = "d";
         }
         ownerTrust = aLine[8];
         creationDate = EnigmailTime.getDateTime(aLine[5], true, false);
         expiryDate = EnigmailTime.getDateTime(aLine[6], true, false);
         subkeyList.push(aLine);
         if (!gUserId) {
           gUserId = EnigConvertGpgToUnicode(aLine[9]);
@@ -752,20 +850,20 @@ function EnigGetKeyDetails(sigListStr) {
         if (!fingerprint) {
           fingerprint = aLine[9];
         }
         break;
     }
   }
 
   var keyDetails = {
-    gUserId: gUserId,
-    calcTrust: calcTrust,
-    ownerTrust: ownerTrust,
-    fingerprint: fingerprint,
-    showPhoto: showPhoto,
-    uidList: uidList,
-    creationDate: creationDate,
-    expiryDate: expiryDate,
-    subkeyList: subkeyList
+    gUserId,
+    calcTrust,
+    ownerTrust,
+    fingerprint,
+    showPhoto,
+    uidList,
+    creationDate,
+    expiryDate,
+    subkeyList,
   };
   return keyDetails;
 }
--- a/mail/extensions/openpgp/content/ui/enigmailEditIdentity.js
+++ b/mail/extensions/openpgp/content/ui/enigmailEditIdentity.js
@@ -3,242 +3,324 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 /* global gAccount: false, gIdentity: false, onOk: false, smimeOnAcceptEditor: false */
 
 "use strict";
 
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
 
-if (!Enigmail) var Enigmail = {};
+if (!Enigmail) {
+  var Enigmail = {};
+}
 
 Enigmail.edit = {
   account: null,
   identity: null,
   enablePgp: null,
   pgpKeyMode: null,
   pgpKeyId: null,
   cryptoChoicesEnabled: null,
   signingPolicy: null, // account specific: by default sign
   encryptionPolicy: null, // account specific: by default encrypt
   pgpMimeMode: null, // account specific: by default pgp/mime
   pgpSignPlainPolicy: null,
   pgpSignEncPolicy: null,
   autoEncryptDrafts: null,
   openPgpSendKeyWithMsg: null,
 
-  onInit: function() {
+  onInit() {
     // initialize all of our elements based on the current identity values....
-    EnigmailFuncs.collapseAdvanced(document.getElementById("enigmail_PrefsBox"), "hidden");
+    EnigmailFuncs.collapseAdvanced(
+      document.getElementById("enigmail_PrefsBox"),
+      "hidden"
+    );
 
     this.enablePgp = document.getElementById("enigmail_enablePgp");
     this.pgpKeyMode = document.getElementById("enigmail_pgpKeyMode");
     this.pgpKeyId = document.getElementById("enigmail_identity.pgpkeyId");
     this.signingPolicy = document.getElementById("enigmail_sign_ifPossible");
-    this.encryptionPolicy = document.getElementById("enigmail_encrypt_ifPossible");
+    this.encryptionPolicy = document.getElementById(
+      "enigmail_encrypt_ifPossible"
+    );
     this.pgpMimeMode = document.getElementById("enigmail_pgpMimeMode");
     this.pgpSignEncPolicy = document.getElementById("enigmail_sign_encrypted");
-    this.pgpSignPlainPolicy = document.getElementById("enigmail_sign_notEncrypted");
-    this.autoEncryptDrafts = document.getElementById("enigmail_autoEncryptDrafts");
-    this.mimePreferOpenPGP = document.getElementById("enigmail_mimePreferOpenPGP");
+    this.pgpSignPlainPolicy = document.getElementById(
+      "enigmail_sign_notEncrypted"
+    );
+    this.autoEncryptDrafts = document.getElementById(
+      "enigmail_autoEncryptDrafts"
+    );
+    this.mimePreferOpenPGP = document.getElementById(
+      "enigmail_mimePreferOpenPGP"
+    );
     this.enableAc = document.getElementById("enigmail_enableAutocrypt");
     this.acPreferEncrypt = document.getElementById("enigmail_acPreferEncrypt");
-    this.isSingleIdEditor = document.getElementById("enigmail_singleId") ? true : false;
-    this.openPgpSendKeyWithMsg = document.getElementById("openpgp.sendKeyWithMsg");
-
-    document.getElementById("enigmail_amPrefAutocryptDesc").innerHTML = EnigmailLocale.getString("amPrefAutocrypt.desc");
+    this.isSingleIdEditor = !!document.getElementById("enigmail_singleId");
+    this.openPgpSendKeyWithMsg = document.getElementById(
+      "openpgp.sendKeyWithMsg"
+    );
 
     if (this.isSingleIdEditor) {
       let acTab = document.getElementById("enigmail_autocryptTab");
       acTab.setAttribute("collapsed", "true");
     }
 
     if (this.identity) {
       this.enablePgp.checked = this.identity.getBoolAttribute("enablePgp");
       this.cryptoChoicesEnabled = this.enablePgp.checked;
 
       var selectedItemId = null;
       var keyPolicy = this.identity.getIntAttribute("pgpKeyMode");
       switch (keyPolicy) {
         case 1:
-          selectedItemId = 'enigmail_keymode_usePgpkeyId';
+          selectedItemId = "enigmail_keymode_usePgpkeyId";
           break;
         default:
-          selectedItemId = 'enigmail_keymode_useFromAddress';
+          selectedItemId = "enigmail_keymode_useFromAddress";
           break;
       }
       this.pgpKeyMode.selectedItem = document.getElementById(selectedItemId);
 
       var mimePolicy = this.identity.getIntAttribute("mimePreferOpenPGP");
       switch (mimePolicy) {
         case 1:
           selectedItemId = "enigmail_mime_preferEnigmail";
           break;
         default:
           selectedItemId = "enigmail_mime_preferSMime";
           break;
       }
-      this.mimePreferOpenPGP.selectedItem = document.getElementById(selectedItemId);
+      this.mimePreferOpenPGP.selectedItem = document.getElementById(
+        selectedItemId
+      );
 
       this.pgpKeyId.value = this.identity.getCharAttribute("pgpkeyId");
-      this.signingPolicy.checked = (this.identity.getIntAttribute("defaultSigningPolicy") > 0);
-      this.encryptionPolicy.checked = (this.identity.getIntAttribute("defaultEncryptionPolicy") > 0);
+      this.signingPolicy.checked =
+        this.identity.getIntAttribute("defaultSigningPolicy") > 0;
+      this.encryptionPolicy.checked =
+        this.identity.getIntAttribute("defaultEncryptionPolicy") > 0;
       this.pgpMimeMode.checked = this.identity.getBoolAttribute("pgpMimeMode");
-      this.pgpSignEncPolicy.checked = this.identity.getBoolAttribute("pgpSignEncrypted");
-      this.pgpSignPlainPolicy.checked = this.identity.getBoolAttribute("pgpSignPlain");
-      this.autoEncryptDrafts.checked = this.identity.getBoolAttribute("autoEncryptDrafts");
-
+      this.pgpSignEncPolicy.checked = this.identity.getBoolAttribute(
+        "pgpSignEncrypted"
+      );
+      this.pgpSignPlainPolicy.checked = this.identity.getBoolAttribute(
+        "pgpSignPlain"
+      );
+      this.autoEncryptDrafts.checked = this.identity.getBoolAttribute(
+        "autoEncryptDrafts"
+      );
     } else {
       this.enablePgp.checked = false;
       this.cryptoChoicesEnabled = false;
       this.pgpMimeMode.checked = true;
       this.pgpSignEncPolicy.checked = true;
       this.autoEncryptDrafts.checked = true;
     }
 
     if (this.account) {
-      this.enableAc.checked = this.account.incomingServer.getBoolValue("enableAutocrypt");
-      this.acPreferEncrypt.checked = (this.account.incomingServer.getIntValue("acPreferEncrypt") > 0);
+      this.enableAc.checked = this.account.incomingServer.getBoolValue(
+        "enableAutocrypt"
+      );
+      this.acPreferEncrypt.checked =
+        this.account.incomingServer.getIntValue("acPreferEncrypt") > 0;
     } else {
       this.enableAc.checked = true;
     }
 
-
     // Disable all locked elements on the panel
     //onLockPreference();
     this.enableAllPrefs();
   },
 
-  onLoadEditor: function() {
-    if (typeof(gAccount) == "object") {
+  onLoadEditor() {
+    if (typeof gAccount == "object") {
       this.account = gAccount;
       this.identity = gIdentity;
     } else if ("arguments" in window) {
       this.identity = window.arguments[0].identity;
       this.account = window.arguments[0].account;
     }
 
     if (this.identity) {
-      var idLabel = EnigmailLocale.getString("identityName", [this.identity.identityName]);
+      var idLabel = EnigmailLocale.getString("identityName", [
+        this.identity.identityName,
+      ]);
       document.getElementById("enigmail_identityName").value = idLabel;
     }
 
     var dlg = document.getElementsByTagName("dialog")[0];
-    dlg.setAttribute("ondialogaccept", "return Enigmail.edit.onAcceptEditor();");
+    dlg.setAttribute(
+      "ondialogaccept",
+      "return Enigmail.edit.onAcceptEditor();"
+    );
 
     this.onInit();
   },
 
-  onAcceptEditor: function() {
+  onAcceptEditor() {
     try {
       if (onOk() === false) {
         return false;
       }
     } catch (ex) {}
     this.onSave();
-    if (typeof(smimeOnAcceptEditor) == "function") {
+    if (typeof smimeOnAcceptEditor == "function") {
       return smimeOnAcceptEditor();
-    } else
-      return true;
+    }
+    return true;
   },
 
-  onSave: function() {
+  onSave() {
     if (!this.identity) {
       this.identity = gIdentity;
     }
     this.identity.setBoolAttribute("enablePgp", this.enablePgp.checked);
     //To attach OpenPGP Key with the mail
-    this.identity.setBoolAttribute("attachPgpKey", this.openPgpSendKeyWithMsg.checked);
+    this.identity.setBoolAttribute(
+      "attachPgpKey",
+      this.openPgpSendKeyWithMsg.checked
+    );
 
     if (this.enablePgp.checked) {
       // PGP is enabled
-      this.identity.setIntAttribute("pgpKeyMode", this.pgpKeyMode.selectedItem.value);
-      this.identity.setIntAttribute("mimePreferOpenPGP", this.mimePreferOpenPGP.selectedItem.value);
+      this.identity.setIntAttribute(
+        "pgpKeyMode",
+        this.pgpKeyMode.selectedItem.value
+      );
+      this.identity.setIntAttribute(
+        "mimePreferOpenPGP",
+        this.mimePreferOpenPGP.selectedItem.value
+      );
       this.identity.setCharAttribute("pgpkeyId", this.pgpKeyId.value);
-      this.identity.setIntAttribute("defaultSigningPolicy", (this.signingPolicy.checked ? 1 : 0));
-      this.identity.setIntAttribute("defaultEncryptionPolicy", (this.encryptionPolicy.checked ? 1 : 0));
+      this.identity.setIntAttribute(
+        "defaultSigningPolicy",
+        this.signingPolicy.checked ? 1 : 0
+      );
+      this.identity.setIntAttribute(
+        "defaultEncryptionPolicy",
+        this.encryptionPolicy.checked ? 1 : 0
+      );
       this.identity.setBoolAttribute("pgpMimeMode", this.pgpMimeMode.checked);
-      this.identity.setBoolAttribute("pgpSignEncrypted", this.pgpSignEncPolicy.checked);
-      this.identity.setBoolAttribute("pgpSignPlain", this.pgpSignPlainPolicy.checked);
-      this.identity.setBoolAttribute("autoEncryptDrafts", this.autoEncryptDrafts.checked);
+      this.identity.setBoolAttribute(
+        "pgpSignEncrypted",
+        this.pgpSignEncPolicy.checked
+      );
+      this.identity.setBoolAttribute(
+        "pgpSignPlain",
+        this.pgpSignPlainPolicy.checked
+      );
+      this.identity.setBoolAttribute(
+        "autoEncryptDrafts",
+        this.autoEncryptDrafts.checked
+      );
     }
 
     if (!this.isSingleIdEditor) {
-      this.account.incomingServer.setBoolValue("enableAutocrypt", this.enableAc.checked);
-      this.account.incomingServer.setIntValue("acPreferEncrypt", this.acPreferEncrypt.checked ? 1 : 0);
+      this.account.incomingServer.setBoolValue(
+        "enableAutocrypt",
+        this.enableAc.checked
+      );
+      this.account.incomingServer.setIntValue(
+        "acPreferEncrypt",
+        this.acPreferEncrypt.checked ? 1 : 0
+      );
     }
   },
 
-  toggleEnable: function() {
-    let newCryptoEnabled = (!this.cryptoChoicesEnabled);
+  toggleEnable() {
+    let newCryptoEnabled = !this.cryptoChoicesEnabled;
 
     this.cryptoChoicesEnabled = newCryptoEnabled;
     this.enableAllPrefs();
   },
 
-  enableAllPrefs: function() {
+  enableAllPrefs() {
     var elem = document.getElementById("enigmail_bcEnablePgp");
     if (this.cryptoChoicesEnabled) {
-      if (elem) elem.removeAttribute("disabled");
-    } else {
-      if (elem) elem.setAttribute("disabled", "true");
+      if (elem) {
+        elem.removeAttribute("disabled");
+      }
+    } else if (elem) {
+      elem.setAttribute("disabled", "true");
     }
 
-    this.enableKeySel(this.cryptoChoicesEnabled && (this.pgpKeyMode.value == 1));
+    this.enableKeySel(this.cryptoChoicesEnabled && this.pgpKeyMode.value == 1);
     this.enableAcSettings();
   },
 
-  enableKeySel: function(enable) {
+  enableKeySel(enable) {
     if (enable) {
-      document.getElementById("enigmail_bcUseKeyId").removeAttribute("disabled");
+      document
+        .getElementById("enigmail_bcUseKeyId")
+        .removeAttribute("disabled");
     } else {
-      document.getElementById("enigmail_bcUseKeyId").setAttribute("disabled", "true");
+      document
+        .getElementById("enigmail_bcUseKeyId")
+        .setAttribute("disabled", "true");
     }
   },
 
-  enableAcSettings: function() {
+  enableAcSettings() {
     if (this.cryptoChoicesEnabled && this.enableAc.checked) {
       this.acPreferEncrypt.removeAttribute("disabled");
     } else {
       this.acPreferEncrypt.setAttribute("disabled", "true");
     }
   },
 
-  handleClick: function(event) {
+  handleClick(event) {
     if (event.target.hasAttribute("href")) {
       EnigmailWindows.openMailTab(event.target.getAttribute("href"));
     }
   },
 
-  selectKeyId: function() {
+  selectKeyId() {
     var resultObj = {};
     var inputObj = {};
     inputObj.dialogHeader = EnigmailLocale.getString("encryptKeyHeader");
     inputObj.options = "single,hidexpired,private,nosending";
     var button = document.getElementById("enigmail_selectPgpKey");
     var label = button.getAttribute("label");
     inputObj.options += ",sendlabel=" + label;
     inputObj.options += ",";
 
-    window.openDialog("chrome://openpgp/content/ui/enigmailKeySelection.xhtml", "", "dialog,modal,centerscreen,resizable", inputObj, resultObj);
+    window.openDialog(
+      "chrome://openpgp/content/ui/enigmailKeySelection.xhtml",
+      "",
+      "dialog,modal,centerscreen,resizable",
+      inputObj,
+      resultObj
+    );
     try {
-      if (resultObj.cancelled) return;
+      if (resultObj.cancelled) {
+        return;
+      }
       var selKey = resultObj.userList[0];
       //selKey = "0x"+selKey.substring(10,18);
       this.pgpKeyId.value = selKey;
     } catch (ex) {
       // cancel pressed -> don't send mail
-      return;
     }
-  }
-
+  },
 };
 
-window.addEventListener("load-enigmail", Enigmail.edit.onLoadEditor.bind(Enigmail.edit), false);
+window.addEventListener(
+  "load-enigmail",
+  Enigmail.edit.onLoadEditor.bind(Enigmail.edit)
+);
 
 document.addEventListener("dialogaccept", function(event) {
   Enigmail.edit.onAcceptEditor();
 });
--- a/mail/extensions/openpgp/content/ui/enigmailKeyImportInfo.js
+++ b/mail/extensions/openpgp/content/ui/enigmailKeyImportInfo.js
@@ -1,25 +1,34 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-var EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-var EnigmailEvents = ChromeUtils.import("chrome://openpgp/content/modules/events.jsm").EnigmailEvents;
-var EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+var EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+var EnigmailEvents = ChromeUtils.import(
+  "chrome://openpgp/content/modules/events.jsm"
+).EnigmailEvents;
+var EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
 
 function onLoad() {
   var dlg = document.getElementById("enigmailKeyImportInfo");
 
   let i, keys;
 
   dlg.getButton("help").setAttribute("hidden", "true");
   dlg.getButton("cancel").setAttribute("hidden", "true");
@@ -46,17 +55,19 @@ function onLoad() {
     let keyId = keyList[i];
 
     if (keyId.search(/^0x/) === 0) {
       keyId = keyId.substr(2).toUpperCase();
     }
     let keyObj = EnigmailKeyRing.getKeyById(keyId);
     if (keyObj && keyObj.fpr) {
       let keyGroupBox = buildKeyGroupBox(keyObj);
-      keyGroupBox.getElementsByClassName("enigmailKeyImportDetails")[0].addEventListener('click', onClickFunc, true);
+      keyGroupBox
+        .getElementsByClassName("enigmailKeyImportDetails")[0]
+        .addEventListener("click", onClickFunc, true);
       keys.push(keyGroupBox);
     }
   }
 
   dlg.getButton("accept").focus();
 
   if (keys.length) {
     let keysInfoBox = document.getElementById("keyInfo"),
@@ -65,17 +76,17 @@ function onLoad() {
       keysCols = document.createXULElement("columns");
 
     for (i = 0; i < 3; i++) {
       keysCols.appendChild(document.createXULElement("column"));
     }
 
     let keysRow;
     for (i = 0; i < keys.length; i++) {
-      if ((i % 3) === 0) {
+      if (i % 3 === 0) {
         keysRow = document.createXULElement("row");
         keysRows.appendChild(keysRow);
       }
       keysRow.appendChild(keys[i]);
     }
 
     keysGrid.appendChild(keysRows);
     keysGrid.appendChild(keysCols);
@@ -85,17 +96,16 @@ function onLoad() {
     EnigmailEvents.dispatchEvent(window.close, 0);
     return;
   }
 
   EnigmailEvents.dispatchEvent(resizeDlg, 0);
 }
 
 function buildKeyGroupBox(keyObj) {
-
   let i,
     groupBox = document.createXULElement("vbox"),
     vbox = document.createXULElement("hbox"),
     caption = document.createXULElement("image"),
     userid = document.createXULElement("label"),
     infoGrid = document.createXULElement("grid"),
     infoColumns = document.createXULElement("columns"),
     infoColId = document.createXULElement("column"),
@@ -117,21 +127,27 @@ function buildKeyGroupBox(keyObj) {
     fprRow2 = document.createXULElement("row");
 
   groupBox.setAttribute("class", "enigmailGroupbox");
   userid.setAttribute("value", keyObj.userId);
   userid.setAttribute("class", "enigmailKeyImportUserId");
   vbox.setAttribute("align", "start");
   caption.setAttribute("class", "enigmailKeyImportCaption");
   infoLabelH1.setAttribute("value", EnigmailLocale.getString("importInfoBits"));
-  infoLabelH2.setAttribute("value", EnigmailLocale.getString("importInfoCreated"));
+  infoLabelH2.setAttribute(
+    "value",
+    EnigmailLocale.getString("importInfoCreated")
+  );
   infoLabelH3.setAttribute("value", "");
   infoLabelB1.setAttribute("value", keyObj.keySize);
   infoLabelB2.setAttribute("value", keyObj.created);
-  infoLabelB3.setAttribute("value", EnigmailLocale.getString("importInfoDetails"));
+  infoLabelB3.setAttribute(
+    "value",
+    EnigmailLocale.getString("importInfoDetails")
+  );
   infoLabelB3.setAttribute("keyid", keyObj.keyId);
   infoLabelB3.setAttribute("class", "enigmailKeyImportDetails");
 
   infoRowHead.appendChild(infoLabelH1);
   infoRowHead.appendChild(infoLabelH2);
   infoRowHead.appendChild(infoLabelH3);
   infoRowHead.setAttribute("class", "enigmailKeyImportHeader");
   infoRowBody.appendChild(infoLabelB1);
@@ -167,20 +183,18 @@ function buildKeyGroupBox(keyObj) {
   groupBox.appendChild(infoGrid);
   groupBox.appendChild(fprLabel);
   groupBox.appendChild(fprGrid);
 
   return groupBox;
 }
 
 function resizeDlg() {
-
   var txt = document.getElementById("keyInfo");
   var box = document.getElementById("outerbox");
-  var dlg = document.getElementById("enigmailKeyImportInfo");
 
   var deltaWidth = window.outerWidth - box.clientWidth;
   var newWidth = txt.scrollWidth + deltaWidth + 20;
 
   if (newWidth > window.screen.width - 50) {
     newWidth = window.screen.width - 50;
   }
 
@@ -188,30 +202,29 @@ function resizeDlg() {
   window.outerWidth = newWidth;
 
   var textHeight = txt.scrollHeight;
   var boxHeight = box.clientHeight;
   var deltaHeight = window.outerHeight - boxHeight;
 
   var newHeight = textHeight + deltaHeight + 25;
 
-
   if (newHeight > window.screen.height - 100) {
     newHeight = window.screen.height - 100;
   }
 
   window.outerHeight = newHeight;
 }
 
 function centerDialog() {
-  if (EnigmailOS.getOS() != "Darwin")
+  if (EnigmailOS.getOS() != "Darwin") {
     document.getElementById("enigmailKeyImportInfo").centerWindowOnScreen();
+  }
 }
 
-
 function dlgClose(buttonNumber) {
   window.arguments[1].value = buttonNumber;
   window.close();
 }
 
 document.addEventListener("dialogaccept", function(event) {
   dlgClose(0);
 });
--- a/mail/extensions/openpgp/content/ui/enigmailKeyManager.js
+++ b/mail/extensions/openpgp/content/ui/enigmailKeyManager.js
@@ -1,53 +1,72 @@
 /*global EnigInitCommon: false, EnigmailDialog: false */
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
 // Uses: chrome://openpgp/content/ui/enigmailCommon.js:
 /* global EnigGetPref: false, EnigGetString: false, EnigFormatFpr: false, EnigGetTrustLabel: false */
 /* global GetEnigmailSvc: false, EnigConfirm: false, EnigAlert: false, EnigShowPhoto: false, EnigFilePicker: false */
 /* global enigGetService: false, EnigGetTempDir: false, EnigReadFileContents: false, EnigGetLocalFileApi: false, EnigAlertPref: false */
 /* global EnigEditKeyTrust: false, EnigEditKeyExpiry: false, EnigSignKey: false, EnigRevokeKey: false, EnigCreateRevokeCert: false */
 /* global EnigLongAlert: false, EnigChangeKeyPwd: false, EnigDownloadKeys: false, EnigSetPref: false, EnigGetTrustCode: false */
-/* global ENIG_KEY_DISABLED: false, ENIG_KEY_NOT_VALID: false, IOSERVICE_CONTRACTID: false, ENIG_LOCAL_FILE_CONTRACTID: false */
+/* global ENIG_KEY_DISABLED: false, ENIG_KEY_NOT_VALID: false, ENIG_LOCAL_FILE_CONTRACTID: false */
 
 // imported packages
-/* global EnigmailLog: false, EnigmailEvents: false, EnigmailKeyRing: false, EnigmailWindows: false, EnigmailKeyEditor: false */
+/* global EnigmailLog: false, EnigmailEvents: false, EnigmailKeyRing: false, EnigmailKeyEditor: false */
 /* global EnigmailKey: false, EnigmailLocale: false, EnigmailPrefs: false, EnigmailConstants: false */
 
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+
 // Initialize enigmailCommon
 EnigInitCommon("enigmailKeyManager");
 
-var EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-var EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-var EnigmailClipboard = ChromeUtils.import("chrome://openpgp/content/modules/clipboard.jsm").EnigmailClipboard;
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-var EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-var EnigmailKeyServer = ChromeUtils.import("chrome://openpgp/content/modules/keyserver.jsm").EnigmailKeyServer;
-var EnigmailWks = ChromeUtils.import("chrome://openpgp/content/modules/webKey.jsm").EnigmailWks;
-var EnigmailSearchCallback = ChromeUtils.import("chrome://openpgp/content/modules/searchCallback.jsm").EnigmailSearchCallback;
-var EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+var EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+var EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+var EnigmailClipboard = ChromeUtils.import(
+  "chrome://openpgp/content/modules/clipboard.jsm"
+).EnigmailClipboard;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+var EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+var EnigmailKeyServer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyserver.jsm"
+).EnigmailKeyServer;
+var EnigmailWks = ChromeUtils.import(
+  "chrome://openpgp/content/modules/webKey.jsm"
+).EnigmailWks;
+var EnigmailSearchCallback = ChromeUtils.import(
+  "chrome://openpgp/content/modules/searchCallback.jsm"
+).EnigmailSearchCallback;
+var EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
 
 const INPUT = 0;
 const RESULT = 1;
 
-const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
-
 var gUserList;
 var gKeyList;
 var gEnigLastSelectedKeys = null;
 var gKeySortList = null;
 var gSearchInput = null;
 var gShowAllKeysElement = null;
 var gTreeChildren = null;
 var gShowInvalidKeys = null;
@@ -76,29 +95,33 @@ function enigmailKeyManagerLoad() {
 
   window.addEventListener("reload-keycache", reloadKeys);
   EnigmailSearchCallback.setup(gSearchInput, gTimeoutId, applyFilter, 200);
 
   if (EnigGetPref("keyManShowAllKeys")) {
     gShowAllKeysElement.setAttribute("checked", "true");
   }
 
-  gUserList.addEventListener('click', onListClick, true);
-  document.getElementById("bcEnableKey").setAttribute("label", EnigGetString("keyMan.disableKey"));
+  gUserList.addEventListener("click", onListClick, true);
+  document
+    .getElementById("bcEnableKey")
+    .setAttribute("label", EnigGetString("keyMan.disableKey"));
   //document.getElementById("pleaseWait").showPopup(gSearchInput, -1, -1, "tooltip", "after_end", "");
-  document.getElementById("statusText").value = EnigGetString("keyMan.loadingKeys");
+  document.getElementById("statusText").value = EnigGetString(
+    "keyMan.loadingKeys"
+  );
   document.getElementById("progressBar").style.visibility = "visible";
   EnigmailEvents.dispatchEvent(loadkeyList, 100, null);
 
   gUserList.view = gKeyListView;
   gSearchInput.focus();
 }
 
 function displayFullList() {
-  return (gShowAllKeysElement.getAttribute("checked") == "true");
+  return gShowAllKeysElement.getAttribute("checked") == "true";
 }
 
 function loadkeyList() {
   EnigmailLog.DEBUG("enigmailKeyManager.js: loadkeyList\n");
 
   sortTree();
   gKeyListView.applyFilter(0);
   document.getElementById("pleaseWait").hidePopup();
@@ -118,52 +141,59 @@ function refreshKeys() {
   for (var i = 0; i < keyList.length; i++) {
     gEnigLastSelectedKeys[keyList[i]] = 1;
   }
 
   buildKeyList(true);
 }
 
 function reloadKeys() {
-
   let i = 0;
   let c = Components.stack;
 
   while (c) {
-    if (c.name == "reloadKeys") i++;
+    if (c.name == "reloadKeys") {
+      i++;
+    }
     c = c.caller;
   }
 
   // detect recursion and don't continue if too much recursion
   // this can happen if the key list is empty
-  if (i < 4) buildKeyList(false);
+  if (i < 4) {
+    buildKeyList(false);
+  }
 }
 
 function buildKeyList(refresh) {
   EnigmailLog.DEBUG("enigmailKeyManager.js: buildKeyList\n");
 
   var keyListObj = {};
 
   if (refresh) {
     EnigmailKeyRing.clearCache();
   }
-  
-  keyListObj = EnigmailKeyRing.getAllKeys(window, getSortColumn(), getSortDirection());
 
-  if (!keyListObj.keySortList) return;
+  keyListObj = EnigmailKeyRing.getAllKeys(
+    window,
+    getSortColumn(),
+    getSortDirection()
+  );
+
+  if (!keyListObj.keySortList) {
+    return;
+  }
 
   gKeyList = keyListObj.keyList;
   gKeySortList = keyListObj.keySortList;
 
   gKeyListView.keysRefreshed();
-  return;
 }
 
 function getSelectedKeys() {
-
   let selList = [];
   let rangeCount = gUserList.view.selection.getRangeCount();
   for (let i = 0; i < rangeCount; i++) {
     let start = {};
     let end = {};
     gUserList.view.selection.getRangeAt(i, start, end);
     for (let c = start.value; c <= end.value; c++) {
       try {
@@ -209,21 +239,27 @@ function enigmailKeyMenu() {
   if (enigGetClipboard().length > 0) {
     document.getElementById("bcClipbrd").removeAttribute("disabled");
   } else {
     document.getElementById("bcClipbrd").setAttribute("disabled", "true");
   }
 
   if (keyList.length >= 1) {
     document.getElementById("bcEnableKey").removeAttribute("disabled");
-    if (gKeyList[keyList[0]].keyUseFor.indexOf("D") > 0 ||
-      gKeyList[keyList[0]].keyTrust.indexOf(ENIG_KEY_DISABLED) >= 0) {
-      document.getElementById("bcEnableKey").setAttribute("label", EnigGetString("keyMan.enableKey"));
+    if (
+      gKeyList[keyList[0]].keyUseFor.indexOf("D") > 0 ||
+      gKeyList[keyList[0]].keyTrust.includes(ENIG_KEY_DISABLED)
+    ) {
+      document
+        .getElementById("bcEnableKey")
+        .setAttribute("label", EnigGetString("keyMan.enableKey"));
     } else {
-      document.getElementById("bcEnableKey").setAttribute("label", EnigGetString("keyMan.disableKey"));
+      document
+        .getElementById("bcEnableKey")
+        .setAttribute("label", EnigGetString("keyMan.disableKey"));
     }
   }
 
   if (keyList.length == 1 && gKeyList[keyList[0]].isOwnerTrustUseful()) {
     document.getElementById("bcSetTrust").removeAttribute("collapsed");
   } else {
     document.getElementById("bcSetTrust").setAttribute("collapsed", "true");
   }
@@ -241,272 +277,322 @@ function enigmailKeyMenu() {
       document.getElementById("bcNoKey").removeAttribute("disabled");
     }
     document.getElementById("bcSignKey").setAttribute("disabled", "true");
     document.getElementById("bcOneKey").setAttribute("disabled", "true");
     document.getElementById("bcDeleteKey").setAttribute("disabled", "true");
   }
 }
 
-
 function onListClick(event) {
-
-  if (event.detail > 2) return;
+  if (event.detail > 2) {
+    return;
+  }
 
   if (event.type === "click") {
     // Mouse event
-    let {
-      row,
-      col
-    } = gTreeFuncs.getCellAt(event.clientX, event.clientY);
+    let { col } = gTreeFuncs.getCellAt(event.clientX, event.clientY);
 
-    if (!col) // not clicked on a valid column (e.g. scrollbar)
+    if (!col) {
+      // not clicked on a valid column (e.g. scrollbar)
       return;
+    }
   }
 
   if (event.detail != 2) {
     return;
   }
 
   // do not propagate double clicks
   event.stopPropagation();
 
   var keyList = getSelectedKeys();
   var keyType = "";
   var uatNum = "";
   if (keyList.length == 1) {
-    var rangeCount = gUserList.view.selection.getRangeCount();
     var start = {};
     var end = {};
     gUserList.view.selection.getRangeAt(0, start, end);
     try {
-      keyType = gUserList.view.getItemAtIndex(start.value).getAttribute("keytype");
-      uatNum = gUserList.view.getItemAtIndex(start.value).getAttribute("uatNum");
+      keyType = gUserList.view
+        .getItemAtIndex(start.value)
+        .getAttribute("keytype");
+      uatNum = gUserList.view
+        .getItemAtIndex(start.value)
+        .getAttribute("uatNum");
     } catch (ex) {}
   }
   if (keyType == "uat") {
     enigShowSpecificPhoto(Number(uatNum));
   } else {
     enigmailKeyDetails();
   }
 }
 
 function enigmailSelectAllKeys() {
   gUserList.view.selection.selectAll();
 }
 
 function enigmailKeyDetails() {
   var keyList = getSelectedKeys();
   if (keyList.length > 0) {
-    if (EnigmailWindows.openKeyDetails(window, gKeyList[keyList[0]].keyId, false)) {
+    if (
+      EnigmailWindows.openKeyDetails(window, gKeyList[keyList[0]].keyId, false)
+    ) {
       refreshKeys();
     }
   }
 }
 
 function enigmailDeleteKey() {
   var keyList = getSelectedKeys();
   var deleteSecret = false;
 
   var enigmailSvc = GetEnigmailSvc();
-  if (!enigmailSvc)
+  if (!enigmailSvc) {
     return;
+  }
 
   if (keyList.length == 1) {
     // one key selected
     var userId = gKeyList[keyList[0]].userId;
     if (gKeyList[keyList[0]].secretAvailable) {
-      if (!EnigConfirm(EnigGetString("deleteSecretKey", userId), EnigGetString("dlg.button.delete"))) return;
+      if (
+        !EnigConfirm(
+          EnigGetString("deleteSecretKey", userId),
+          EnigGetString("dlg.button.delete")
+        )
+      ) {
+        return;
+      }
       deleteSecret = true;
-    } else {
-      if (!EnigConfirm(EnigGetString("deletePubKey", userId), EnigGetString("dlg.button.delete"))) return;
+    } else if (
+      !EnigConfirm(
+        EnigGetString("deletePubKey", userId),
+        EnigGetString("dlg.button.delete")
+      )
+    ) {
+      return;
     }
   } else {
     // several keys selected
     for (var i = 0; i < keyList.length; i++) {
-      if (gKeyList[keyList[i]].secretAvailable)
+      if (gKeyList[keyList[i]].secretAvailable) {
         deleteSecret = true;
+      }
     }
 
     if (deleteSecret) {
-      if (!EnigConfirm(EnigGetString("deleteMix"), EnigGetString("dlg.button.delete"))) return;
-    } else {
-      if (!EnigConfirm(EnigGetString("deleteSelectedPubKey"), EnigGetString("dlg.button.delete"))) return;
+      if (
+        !EnigConfirm(
+          EnigGetString("deleteMix"),
+          EnigGetString("dlg.button.delete")
+        )
+      ) {
+        return;
+      }
+    } else if (
+      !EnigConfirm(
+        EnigGetString("deleteSelectedPubKey"),
+        EnigGetString("dlg.button.delete")
+      )
+    ) {
+      return;
     }
   }
 
+  const cApi = EnigmailCryptoAPI();
   for (let j in keyList) {
-    RNP.deleteKey(gKeyList[keyList[j]].fpr, deleteSecret);
+    cApi.sync(cApi.deleteKey(gKeyList[keyList[j]].fpr, deleteSecret));
   }
   clearKeyCache();
 }
 
-
 function enigmailEnableKey() {
   throw new Error("Not implemented");
 }
 
 function enigShowPhoto() {
-
   var keyList = getSelectedKeys();
   var keyType = "";
   var uatNum = "";
   if (keyList.length == 1) {
-    var rangeCount = gUserList.view.selection.getRangeCount();
     var start = {};
     var end = {};
     gUserList.view.selection.getRangeAt(0, start, end);
     try {
-      keyType = gUserList.view.getItemAtIndex(start.value).getAttribute("keytype");
-      uatNum = gUserList.view.getItemAtIndex(start.value).getAttribute("uatNum");
+      keyType = gUserList.view
+        .getItemAtIndex(start.value)
+        .getAttribute("keytype");
+      uatNum = gUserList.view
+        .getItemAtIndex(start.value)
+        .getAttribute("uatNum");
     } catch (ex) {}
 
     if (keyType == "uat") {
       enigShowSpecificPhoto(uatNum);
       return;
     }
   }
 
   enigShowSpecificPhoto(null);
 }
 
 function enigShowSpecificPhoto(uatNumber) {
   var keyList = getSelectedKeys();
 
-  EnigShowPhoto(gKeyList[keyList[0]].keyId, gKeyList[keyList[0]].userId, uatNumber);
+  EnigShowPhoto(
+    gKeyList[keyList[0]].keyId,
+    gKeyList[keyList[0]].userId,
+    uatNumber
+  );
 }
 
 function enigmailAddPhoto() {
   var keyList = getSelectedKeys();
   keyMgrAddPhoto(gKeyList[keyList[0]].userId, gKeyList[keyList[0]].keyId);
-
 }
 
 function keyMgrAddPhoto(userId, keyId) {
   throw new Error("Not implemented");
 }
 
 function enigCreateKeyMsg() {
   var enigmailSvc = GetEnigmailSvc();
-  if (!enigmailSvc)
+  if (!enigmailSvc) {
     return;
+  }
 
   var keyList = getSelectedKeyIds();
   if (keyList.length === 0) {
     EnigAlert(EnigGetString("noKeySelected"));
     return;
   }
 
   var tmpDir = EnigGetTempDir();
   var tmpFile;
   try {
-    tmpFile = Cc[ENIG_LOCAL_FILE_CONTRACTID].createInstance(EnigGetLocalFileApi());
+    tmpFile = Cc[ENIG_LOCAL_FILE_CONTRACTID].createInstance(
+      EnigGetLocalFileApi()
+    );
     tmpFile.initWithPath(tmpDir);
     if (!(tmpFile.isDirectory() && tmpFile.isWritable())) {
       EnigAlert(EnigGetString("noTempDir"));
       return;
     }
   } catch (ex) {}
   tmpFile.append("key.asc");
   tmpFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
 
-
-
   // save file
   var exitCodeObj = {};
   var errorMsgObj = {};
-  EnigmailKeyRing.extractKey(false, "0x" + keyList.join(" 0x"), tmpFile, exitCodeObj, errorMsgObj);
+  EnigmailKeyRing.extractKey(
+    false,
+    "0x" + keyList.join(" 0x"),
+    tmpFile,
+    exitCodeObj,
+    errorMsgObj
+  );
   if (exitCodeObj.value !== 0) {
     EnigAlert(errorMsgObj.value);
     return;
   }
 
   // create attachment
-  var ioServ = Cc[IOSERVICE_CONTRACTID].getService(Ci.nsIIOService);
+  var ioServ = Services.io;
   var tmpFileURI = ioServ.newFileURI(tmpFile);
-  var keyAttachment = Cc["@mozilla.org/messengercompose/attachment;1"].createInstance(Ci.nsIMsgAttachment);
+  var keyAttachment = Cc[
+    "@mozilla.org/messengercompose/attachment;1"
+  ].createInstance(Ci.nsIMsgAttachment);
   keyAttachment.url = tmpFileURI.spec;
   if (keyList.length == 1) {
     keyAttachment.name = "0x" + keyList[0] + ".asc";
   } else {
     keyAttachment.name = "pgpkeys.asc";
   }
   keyAttachment.temporary = true;
   keyAttachment.contentType = "application/pgp-keys";
 
   // create Msg
-  var msgCompFields = Cc["@mozilla.org/messengercompose/composefields;1"].createInstance(Ci.nsIMsgCompFields);
+  var msgCompFields = Cc[
+    "@mozilla.org/messengercompose/composefields;1"
+  ].createInstance(Ci.nsIMsgCompFields);
   msgCompFields.addAttachment(keyAttachment);
 
-  var acctManager = Cc["@mozilla.org/messenger/account-manager;1"].createInstance(Ci.nsIMsgAccountManager);
+  var msgCompSvc = Cc["@mozilla.org/messengercompose;1"].getService(
+    Ci.nsIMsgComposeService
+  );
 
-  var msgCompSvc = Cc["@mozilla.org/messengercompose;1"].getService(Ci.nsIMsgComposeService);
-
-  var msgCompParam = Cc["@mozilla.org/messengercompose/composeparams;1"].createInstance(Ci.nsIMsgComposeParams);
+  var msgCompParam = Cc[
+    "@mozilla.org/messengercompose/composeparams;1"
+  ].createInstance(Ci.nsIMsgComposeParams);
   msgCompParam.composeFields = msgCompFields;
   msgCompParam.identity = EnigmailFuncs.getDefaultIdentity();
   msgCompParam.type = Ci.nsIMsgCompType.New;
   msgCompParam.format = Ci.nsIMsgCompFormat.Default;
   msgCompParam.originalMsgURI = "";
   msgCompSvc.OpenComposeWindowWithParams("", msgCompParam);
 }
 
 function createNewMail() {
-
   var keyList = getSelectedKeys();
   if (keyList.length === 0) {
     EnigmailDialog.info(window, EnigGetString("noKeySelected"));
     return;
   }
 
   var addresses = [];
   var rangeCount = gUserList.view.selection.getRangeCount();
   var start = {};
   var end = {};
-  var keyType,
-    keyNum,
-    r,
-    i;
+  var keyType, keyNum, r, i;
 
   for (i = 0; i < rangeCount; i++) {
     gUserList.view.selection.getRangeAt(i, start, end);
 
     for (r = start.value; r <= end.value; r++) {
       try {
         keyType = gUserList.view.getItemAtIndex(r).getAttribute("keytype");
         keyNum = gUserList.view.getItemAtIndex(r).getAttribute("keyNum");
 
         if (keyType == "uid") {
-          var uidNum = Number(gUserList.view.getItemAtIndex(r).getAttribute("uidNum"));
+          var uidNum = Number(
+            gUserList.view.getItemAtIndex(r).getAttribute("uidNum")
+          );
           addresses.push(gKeyList[keyNum].userIds[uidNum].userId);
-        } else
+        } else {
           addresses.push(gKeyList[keyNum].userId);
+        }
       } catch (ex) {}
     }
   }
 
   // create Msg
-  var msgCompFields = Cc["@mozilla.org/messengercompose/composefields;1"].createInstance(Ci.nsIMsgCompFields);
+  var msgCompFields = Cc[
+    "@mozilla.org/messengercompose/composefields;1"
+  ].createInstance(Ci.nsIMsgCompFields);
   msgCompFields.to = addresses.join(", ");
 
-  var acctManager = Cc["@mozilla.org/messenger/account-manager;1"].createInstance(Ci.nsIMsgAccountManager);
+  var msgCompSvc = Cc["@mozilla.org/messengercompose;1"].getService(
+    Ci.nsIMsgComposeService
+  );
 
-  var msgCompSvc = Cc["@mozilla.org/messengercompose;1"].getService(Ci.nsIMsgComposeService);
-
-  var msgCompParam = Cc["@mozilla.org/messengercompose/composeparams;1"].createInstance(Ci.nsIMsgComposeParams);
+  var msgCompParam = Cc[
+    "@mozilla.org/messengercompose/composeparams;1"
+  ].createInstance(Ci.nsIMsgComposeParams);
   msgCompParam.composeFields = msgCompFields;
   msgCompParam.identity = EnigmailFuncs.getDefaultIdentity();
   msgCompParam.type = Ci.nsIMsgCompType.New;
   msgCompParam.format = Ci.nsIMsgCompFormat.Default;
   msgCompParam.originalMsgURI = "";
   msgCompSvc.OpenComposeWindowWithParams("", msgCompParam);
 }
 
 function enigEditKeyTrust() {
-
   var keyList = getSelectedKeys();
   if (keyList.length === 0) {
     EnigmailDialog.info(window, EnigGetString("noKeySelected"));
     return;
   }
   var userIdList = [];
   var keyIds = [];
   for (var i = 0; i < keyList.length; i++) {
@@ -515,17 +601,16 @@ function enigEditKeyTrust() {
   }
 
   if (EnigEditKeyTrust(userIdList, keyIds)) {
     refreshKeys();
   }
 }
 
 function enigEditKeyExpiry() {
-
   var keyList = getSelectedKeys();
   if (keyList.length === 0) {
     EnigmailDialog.info(window, EnigGetString("noKeySelected"));
     return;
   }
   var userIdList = [];
   var keyIds = [];
   for (var i = 0; i < keyList.length; i++) {
@@ -533,42 +618,48 @@ function enigEditKeyExpiry() {
     keyIds.push(gKeyList[keyList[i]].keyId);
   }
 
   if (EnigEditKeyExpiry(userIdList, keyIds)) {
     refreshKeys();
   }
 }
 
-
 function enigSignKey() {
   var keyList = getSelectedKeys();
   if (keyList.length === 0) {
     EnigmailDialog.info(window, EnigGetString("noKeySelected"));
     return;
   }
-  if (EnigSignKey(gKeyList[keyList[0]].userId, gKeyList[keyList[0]].keyId, null)) {
+  if (
+    EnigSignKey(gKeyList[keyList[0]].userId, gKeyList[keyList[0]].keyId, null)
+  ) {
     refreshKeys();
   }
 }
 
 function enigmailRevokeKey() {
   var keyList = getSelectedKeys();
-  EnigRevokeKey(gKeyList[keyList[0]].keyId, gKeyList[keyList[0]].userId, function _revokeKeyCb(success) {
-    if (success) refreshKeys();
-  });
+  EnigRevokeKey(
+    gKeyList[keyList[0]].keyId,
+    gKeyList[keyList[0]].userId,
+    function(success) {
+      if (success) {
+        refreshKeys();
+      }
+    }
+  );
 }
 
 function enigCreateRevokeCert() {
   var keyList = getSelectedKeys();
 
   EnigCreateRevokeCert(gKeyList[keyList[0]].keyId, gKeyList[keyList[0]].userId);
 }
 
-
 function enigmailExportKeys() {
   var keyList = getSelectedKeys();
   if (keyList.length === 0) {
     EnigmailDialog.info(window, EnigGetString("noKeySelected"));
     return;
   }
 
   // check whether we want to export a private key anywhere in the key list
@@ -583,236 +674,305 @@ function enigmailExportKeys() {
   if (secretFound) {
     // double check that also the pivate keys shall be exportet
     var r = EnigmailDialog.msgBox(window, {
       msgtext: EnigGetString("exportSecretKey"),
       dialogTitle: EnigGetString("enigConfirm"),
       button1: EnigGetString("keyMan.button.exportPubKey"),
       button2: EnigGetString("keyMan.button.exportSecKey"),
       cancelButton: ":cancel",
-      iconType: EnigmailConstants.ICONTYPE_QUESTION
+      iconType: EnigmailConstants.ICONTYPE_QUESTION,
     });
     switch (r) {
       case 0: // export pub key only
         break;
       case 1: // export secret key
         exportSecretKey = true;
         break;
-      default: // cancel
+      default:
+        // cancel
         return;
     }
   }
 
   var enigmailSvc = GetEnigmailSvc();
-  if (!enigmailSvc)
+  if (!enigmailSvc) {
     return;
+  }
   var defaultFileName;
   if (keyList.length == 1) {
-
     defaultFileName = gKeyList[keyList[0]].userId.replace(/[<>]/g, "");
     if (exportSecretKey) {
-      defaultFileName = EnigGetString("specificPubSecKeyFilename", defaultFileName, gKeyList[keyList[0]].keyId) + ".asc";
+      defaultFileName =
+        EnigGetString(
+          "specificPubSecKeyFilename",
+          defaultFileName,
+          gKeyList[keyList[0]].keyId
+        ) + ".asc";
     } else {
-      defaultFileName = EnigGetString("specificPubKeyFilename", defaultFileName, gKeyList[keyList[0]].keyId) + ".asc";
+      defaultFileName =
+        EnigGetString(
+          "specificPubKeyFilename",
+          defaultFileName,
+          gKeyList[keyList[0]].keyId
+        ) + ".asc";
     }
+  } else if (exportSecretKey) {
+    defaultFileName = EnigGetString("defaultPubSecKeyFilename") + ".asc";
   } else {
-    if (exportSecretKey) {
-      defaultFileName = EnigGetString("defaultPubSecKeyFilename") + ".asc";
-    } else {
-      defaultFileName = EnigGetString("defaultPubKeyFilename") + ".asc";
-    }
+    defaultFileName = EnigGetString("defaultPubKeyFilename") + ".asc";
   }
 
   var FilePickerLabel = "";
 
   if (exportSecretKey) {
     FilePickerLabel = EnigGetString("exportKeypairToFile");
   } else {
     FilePickerLabel = EnigGetString("exportToFile");
   }
-  var outFile = EnigFilePicker(FilePickerLabel,
-    "", true, "*.asc",
-    defaultFileName, [EnigGetString("asciiArmorFile"), "*.asc"]);
-  if (!outFile) return;
+  var outFile = EnigFilePicker(
+    FilePickerLabel,
+    "",
+    true,
+    "*.asc",
+    defaultFileName,
+    [EnigGetString("asciiArmorFile"), "*.asc"]
+  );
+  if (!outFile) {
+    return;
+  }
 
   var keyListStr = "0x" + getSelectedKeyIds().join(" 0x");
   var exitCodeObj = {};
   var errorMsgObj = {};
-  EnigmailKeyRing.extractKey(exportSecretKey, keyListStr, outFile, exitCodeObj, errorMsgObj);
+  EnigmailKeyRing.extractKey(
+    exportSecretKey,
+    keyListStr,
+    outFile,
+    exitCodeObj,
+    errorMsgObj
+  );
   if (exitCodeObj.value !== 0) {
     EnigAlert(EnigGetString("saveKeysFailed") + "\n\n" + errorMsgObj.value);
   } else {
     EnigmailDialog.info(window, EnigGetString("saveKeysOK"));
   }
 }
 
 function enigmailManageUids() {
   var keyList = getSelectedKeys();
   var inputObj = {
     keyId: gKeyList[keyList[0]].keyId,
-    ownKey: gKeyList[keyList[0]].secretAvailable
+    ownKey: gKeyList[keyList[0]].secretAvailable,
   };
   var resultObj = {
-    refresh: false
+    refresh: false,
   };
-  window.openDialog("chrome://openpgp/content/ui/enigmailManageUidDlg.xhtml",
-    "", "dialog,modal,centerscreen,resizable=yes", inputObj, resultObj);
+  window.openDialog(
+    "chrome://openpgp/content/ui/enigmailManageUidDlg.xhtml",
+    "",
+    "dialog,modal,centerscreen,resizable=yes",
+    inputObj,
+    resultObj
+  );
   if (resultObj.refresh) {
     refreshKeys();
   }
 }
 
 function enigmailChangePwd() {
   var keyList = getSelectedKeys();
   EnigChangeKeyPwd(gKeyList[keyList[0]].keyId, gKeyList[keyList[0]].userId);
 }
 
-
 function enigGetClipboard() {
-  return EnigmailClipboard.getClipboardContent(window, Ci.nsIClipboard.kGlobalClipboard);
+  return EnigmailClipboard.getClipboardContent(
+    window,
+    Ci.nsIClipboard.kGlobalClipboard
+  );
 }
 
 function enigmailImportFromClipbrd() {
   var enigmailSvc = GetEnigmailSvc();
-  if (!enigmailSvc)
+  if (!enigmailSvc) {
     return;
+  }
 
-  if (!EnigConfirm(EnigGetString("importFromClip"), EnigGetString("keyMan.button.import"))) {
+  if (
+    !EnigConfirm(
+      EnigGetString("importFromClip"),
+      EnigGetString("keyMan.button.import")
+    )
+  ) {
     return;
   }
 
   var cBoardContent = enigGetClipboard();
   var errorMsgObj = {};
   var preview = EnigmailKey.getKeyListFromKeyBlock(cBoardContent, errorMsgObj);
   var exitStatus = -1;
 
   if (preview.length > 0) {
     if (preview.length == 1) {
-      exitStatus = EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("doImportOne", [preview[0].name, preview[0].id]));
+      exitStatus = EnigmailDialog.confirmDlg(
+        window,
+        EnigmailLocale.getString("doImportOne", [
+          preview[0].name,
+          preview[0].id,
+        ])
+      );
     } else {
-      exitStatus = EnigmailDialog.confirmDlg(window,
+      exitStatus = EnigmailDialog.confirmDlg(
+        window,
         EnigmailLocale.getString("doImportMultiple", [
-          preview.map(function(a) {
-            return "\t" + a.name + " (" + a.id + ")";
-          }).join("\n")
-        ]));
+          preview
+            .map(function(a) {
+              return "\t" + a.name + " (" + a.id + ")";
+            })
+            .join("\n"),
+        ])
+      );
     }
 
     if (exitStatus) {
       // import
-      var r = EnigmailKeyRing.importKey(window, false, cBoardContent, "", errorMsgObj);
+      EnigmailKeyRing.importKey(window, false, cBoardContent, "", errorMsgObj);
       var keyList = preview.map(function(a) {
         return a.id;
       });
       EnigmailDialog.keyImportDlg(window, keyList);
       refreshKeys();
     }
   }
 }
 
 function enigmailCopyToClipbrd() {
   var enigmailSvc = GetEnigmailSvc();
-  if (!enigmailSvc)
+  if (!enigmailSvc) {
     return;
+  }
 
   var keyList = getSelectedKeyIds();
   if (keyList.length === 0) {
     EnigmailDialog.info(window, EnigGetString("noKeySelected"));
     return;
   }
   var exitCodeObj = {};
   var errorMsgObj = {};
-  var keyData = EnigmailKeyRing.extractKey(0, "0x" + keyList.join(" 0x"), null, exitCodeObj, errorMsgObj);
+  var keyData = EnigmailKeyRing.extractKey(
+    0,
+    "0x" + keyList.join(" 0x"),
+    null,
+    exitCodeObj,
+    errorMsgObj
+  );
   if (exitCodeObj.value !== 0) {
-    EnigAlert(EnigGetString("copyToClipbrdFailed") + "\n\n" + errorMsgObj.value);
+    EnigAlert(
+      EnigGetString("copyToClipbrdFailed") + "\n\n" + errorMsgObj.value
+    );
     return;
   }
   if (EnigmailClipboard.setClipboardContent(keyData)) {
-    EnigmailLog.DEBUG("enigmailKeyManager.js: enigmailImportFromClipbrd: set clipboard data\n");
+    EnigmailLog.DEBUG(
+      "enigmailKeyManager.js: enigmailImportFromClipbrd: set clipboard data\n"
+    );
     EnigmailDialog.info(window, EnigGetString("copyToClipbrdOK"));
   } else {
     EnigAlert(EnigGetString("copyToClipbrdFailed"));
   }
 }
 
 function enigmailSearchKey() {
   var inputObj = {
-    searchList: null
+    searchList: null,
   };
   var resultObj = {};
 
   EnigDownloadKeys(inputObj, resultObj);
 
   if (resultObj.importedKeys > 0) {
     refreshKeys();
   }
 }
 
-
 function enigmailUploadKeys() {
   accessKeyServer(EnigmailConstants.UPLOAD_KEY, enigmailUploadKeysCb);
 }
 
 function enigmailUploadKeysCb(exitCode, errorMsg, msgBox) {
   if (msgBox) {
     if (exitCode !== 0) {
       EnigAlert(EnigGetString("sendKeysFailed") + "\n" + errorMsg);
     }
   } else {
-    return (EnigGetString(exitCode === 0 ? "sendKeysOk" : "sendKeysFailed"));
+    return EnigGetString(exitCode === 0 ? "sendKeysOk" : "sendKeysFailed");
   }
   return "";
 }
 
 function enigmailUploadToWkd() {
   let selKeyList = getSelectedKeys();
   let keyList = [];
   for (let i = 0; i < selKeyList.length; i++) {
     keyList.push(gKeyList[selKeyList[i]]);
   }
 
-  EnigmailWks.wksUpload(keyList, window).then(result => {
-    if (result.length > 0) {
-      EnigmailDialog.info(window, EnigmailLocale.getString("sendKeysOk"));
-    } else {
-      if (keyList.length === 1) {
-        EnigmailDialog.alert(window, EnigmailLocale.getString("sendKeysFailed") + "\n\n" +
-          EnigmailLocale.getString("noWksIdentity", keyList[0].userId));
+  EnigmailWks.wksUpload(keyList, window)
+    .then(result => {
+      if (result.length > 0) {
+        EnigmailDialog.info(window, EnigmailLocale.getString("sendKeysOk"));
+      } else if (keyList.length === 1) {
+        EnigmailDialog.alert(
+          window,
+          EnigmailLocale.getString("sendKeysFailed") +
+            "\n\n" +
+            EnigmailLocale.getString("noWksIdentity", keyList[0].userId)
+        );
       } else {
-        EnigmailDialog.alert(window, EnigmailLocale.getString("wksUpload.noKeySupported"));
+        EnigmailDialog.alert(
+          window,
+          EnigmailLocale.getString("wksUpload.noKeySupported")
+        );
       }
-    }
-  }).catch(error => {
-    EnigmailDialog.alert(window.EnigmailLocale.getString("sendKeysFailed") + "\n" + error);
-  });
+    })
+    .catch(error => {
+      EnigmailDialog.alert(
+        window.EnigmailLocale.getString("sendKeysFailed") + "\n" + error
+      );
+    });
 }
 
 function enigmailReceiveKey() {
   accessKeyServer(EnigmailConstants.DOWNLOAD_KEY, enigmailReceiveKeyCb);
 }
 
 function userAcceptsWarning(warningMessage) {
   if (!EnigGetPref("warnRefreshAll")) {
     return true;
   }
 
   let checkedObj = {};
 
-  let confirm = EnigmailDialog.msgBox(window, {
-      msgtext: warningMessage,
-      checkboxLabel: EnigGetString("dlgNoPrompt"),
-      button1: EnigGetString("dlg.button.continue"),
-      cancelButton: ":cancel",
-      iconType: EnigmailConstants.ICONTYPE_QUESTION,
-      dialogTitle: EnigmailLocale.getString("enigConfirm")
-    },
-    checkedObj) === 0;
+  let confirm =
+    EnigmailDialog.msgBox(
+      window,
+      {
+        msgtext: warningMessage,
+        checkboxLabel: EnigGetString("dlgNoPrompt"),
+        button1: EnigGetString("dlg.button.continue"),
+        cancelButton: ":cancel",
+        iconType: EnigmailConstants.ICONTYPE_QUESTION,
+        dialogTitle: EnigmailLocale.getString("enigConfirm"),
+      },
+      checkedObj
+    ) === 0;
 
-  if (checkedObj.value)
+  if (checkedObj.value) {
     EnigSetPref("warnRefreshAll", false);
+  }
   return confirm;
 }
 
 function userAcceptsRefreshWarning() {
   if (EnigmailPrefs.getPref("keyRefreshOn") === true) {
     return userAcceptsWarning(EnigGetString("refreshKeyServiceOn.warn"));
   }
   return userAcceptsWarning(EnigGetString("refreshKey.warn"));
@@ -832,32 +992,33 @@ function enigmailDowloadContactKeysEngin
   for (let addressBook of abManager.directories) {
     if (addressBook instanceof Ci.nsIAbDirectory) {
       // or nsIAbItem or nsIAbCollection
       // ask for confirmation for each address book:
       var doIt = EnigmailDialog.confirmDlg(
         window,
         EnigGetString("downloadContactsKeys.importFrom", addressBook.dirName),
         EnigGetString("dlgYes"),
-        EnigGetString("dlg.button.skip"));
+        EnigGetString("dlg.button.skip")
+      );
       if (!doIt) {
         continue; // SKIP this address book
       }
 
       for (let card of addressBook.childCards) {
         try {
           let email = card.getPropertyAsAString("PrimaryEmail");
-          if (email && email.indexOf("@") >= 0) {
+          if (email && email.includes("@")) {
             emails.push(email);
           }
         } catch (e) {}
 
         try {
           let email = card.getPropertyAsAString("SecondEmail");
-          if (email && email.indexOf("@") >= 0) {
+          if (email && email.includes("@")) {
             emails.push(email);
           }
         } catch (e) {}
       }
     }
   }
 
   // list of emails might be emoty here, in which case we do nothing
@@ -875,301 +1036,366 @@ function enigmailDowloadContactKeysEngin
       emails.splice(i, 1);
     } else {
       i = i + 1;
     }
   }
 
   var inputObj = {
     searchList: emails,
-    autoKeyServer: EnigmailPrefs.getPref("autoKeyServerSelection") ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0] : null
+    autoKeyServer: EnigmailPrefs.getPref("autoKeyServerSelection")
+      ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0]
+      : null,
   };
   var resultObj = {};
 
   EnigmailWindows.downloadKeys(window, inputObj, resultObj);
 
   if (resultObj.importedKeys > 0) {
     refreshKeys();
   }
 }
 
 function enigmailDownloadContactKeys() {
-
-  var doIt = EnigmailDialog.confirmPref(window,
+  var doIt = EnigmailDialog.confirmPref(
+    window,
     EnigGetString("downloadContactsKeys.warn"),
     "warnDownloadContactKeys",
     EnigGetString("dlg.button.continue"),
-    EnigGetString("dlg.button.cancel"));
+    EnigGetString("dlg.button.cancel")
+  );
 
-  if (doIt) enigmailDowloadContactKeysEngine();
+  if (doIt) {
+    enigmailDowloadContactKeysEngine();
+  }
 }
 
 function displayResult(arrayOfMsgText) {
   EnigmailDialog.info(window, arrayOfMsgText.join("\n"));
 }
 
 function enigmailReceiveKeyCb(exitCode, errorMsg, msgBox) {
   EnigmailLog.DEBUG("enigmailKeyManager.js: enigmailReceiveKeyCb\n");
   if (msgBox) {
     if (exitCode === 0) {
       refreshKeys();
-      EnigmailEvents.dispatchEvent(displayResult, 100, [EnigGetString("receiveKeysOk"), errorMsg]);
+      EnigmailEvents.dispatchEvent(displayResult, 100, [
+        EnigGetString("receiveKeysOk"),
+        errorMsg,
+      ]);
     } else {
-      EnigmailEvents.dispatchEvent(displayResult, 100, [EnigGetString("receiveKeysFailed"), errorMsg]);
+      EnigmailEvents.dispatchEvent(displayResult, 100, [
+        EnigGetString("receiveKeysFailed"),
+        errorMsg,
+      ]);
     }
   } else {
-    return (EnigGetString(exitCode === 0 ? "receiveKeysOk" : "receiveKeysFailed"));
+    return EnigGetString(
+      exitCode === 0 ? "receiveKeysOk" : "receiveKeysFailed"
+    );
   }
   return "";
 }
 
-
 function addToPRRule() {
   var keyList = getSelectedKeys();
   if (keyList.length === 0) {
     EnigmailDialog.info(window, EnigGetString("noKeySelected"));
     return;
   }
 
   var enigmailSvc = GetEnigmailSvc();
-  if (!enigmailSvc)
+  if (!enigmailSvc) {
     return;
+  }
 
   var inputObj = {
     keyId: gKeyList[keyList[0]].keyId,
-    userId: gKeyList[keyList[0]].userId
+    userId: gKeyList[keyList[0]].userId,
   };
-  window.openDialog("chrome://openpgp/content/ui/enigmailSelectRule.xhtml",
-    "", "dialog,modal,centerscreen", inputObj);
-
+  window.openDialog(
+    "chrome://openpgp/content/ui/enigmailSelectRule.xhtml",
+    "",
+    "dialog,modal,centerscreen",
+    inputObj
+  );
 }
 
 function enigmailImportKeysFromUrl() {
   var value = {
-    "value": ""
+    value: "",
   };
-  if (EnigmailDialog.promptValue(window, EnigGetString("importFromUrl"), value)) {
-    var p = new Promise(
-      function(resolve, reject) {
-        var cbFunc = function _cb(data) {
-          EnigmailLog.DEBUG("enigmailImportKeysFromUrl: _cbFunc()\n");
-          var errorMsgObj = {};
+  if (
+    EnigmailDialog.promptValue(window, EnigGetString("importFromUrl"), value)
+  ) {
+    var p = new Promise(function(resolve, reject) {
+      var cbFunc = function(data) {
+        EnigmailLog.DEBUG("enigmailImportKeysFromUrl: _cbFunc()\n");
+        var errorMsgObj = {};
+
+        // preview
+        var preview = EnigmailKey.getKeyListFromKeyBlock(data, errorMsgObj);
+        var exitStatus = -1;
 
-          // preview
-          var preview = EnigmailKey.getKeyListFromKeyBlock(data, errorMsgObj);
-          var exitStatus = -1;
-
-          if (preview.length > 0) {
-            if (preview.length == 1) {
-              exitStatus = EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("doImportOne", [preview[0].name, preview[0].id]));
-            } else {
-              exitStatus = EnigmailDialog.confirmDlg(window,
-                EnigmailLocale.getString("doImportMultiple", [
-                  preview.map(function(a) {
+        if (preview.length > 0) {
+          if (preview.length == 1) {
+            exitStatus = EnigmailDialog.confirmDlg(
+              window,
+              EnigmailLocale.getString("doImportOne", [
+                preview[0].name,
+                preview[0].id,
+              ])
+            );
+          } else {
+            exitStatus = EnigmailDialog.confirmDlg(
+              window,
+              EnigmailLocale.getString("doImportMultiple", [
+                preview
+                  .map(function(a) {
                     return "\t" + a.name + " (" + a.id + ")";
-                  }).join("\n")
-                ]));
-            }
+                  })
+                  .join("\n"),
+              ])
+            );
+          }
 
-            if (exitStatus) {
-              EnigmailKeyRing.importKey(window, false, data, "", errorMsgObj);
-              errorMsgObj.preview = preview;
-              resolve(errorMsgObj);
-            }
+          if (exitStatus) {
+            EnigmailKeyRing.importKey(window, false, data, "", errorMsgObj);
+            errorMsgObj.preview = preview;
+            resolve(errorMsgObj);
           }
-        };
+        }
+      };
 
-        try {
-          var bufferListener = EnigmailStreams.newStringStreamListener(cbFunc);
-          var ioServ = Cc[IOSERVICE_CONTRACTID].getService(Components.interfaces.nsIIOService);
-          var msgUri = ioServ.newURI(value.value, null, null);
+      try {
+        var bufferListener = EnigmailStreams.newStringStreamListener(cbFunc);
+        var ioServ = Services.io;
+        var msgUri = ioServ.newURI(value.value);
 
-          var channel = EnigmailStreams.createChannel(msgUri);
-          channel.asyncOpen(bufferListener, msgUri);
-        } catch (ex) {
-          var err = {
-            value: ex
-          };
-          reject(err);
-        }
+        var channel = EnigmailStreams.createChannel(msgUri);
+        channel.asyncOpen(bufferListener, msgUri);
+      } catch (ex) {
+        var err = {
+          value: ex,
+        };
+        reject(err);
       }
-    );
+    });
 
     p.then(function(errorMsgObj) {
-        var keyList = errorMsgObj.preview.map(function(a) {
-          return a.id;
-        });
-        EnigmailDialog.keyImportDlg(window, keyList);
-        refreshKeys();
-      })
-      .catch(function(reason) {
-        EnigmailDialog.alert(window, EnigGetString("generalError", [reason.value]));
+      var keyList = errorMsgObj.preview.map(function(a) {
+        return a.id;
       });
+      EnigmailDialog.keyImportDlg(window, keyList);
+      refreshKeys();
+    }).catch(function(reason) {
+      EnigmailDialog.alert(
+        window,
+        EnigGetString("generalError", [reason.value])
+      );
+    });
   }
 }
 
 function initiateAcKeyTransfer() {
   EnigmailWindows.inititateAcSetupMessage();
 }
 
-
 //
 // ----- key filtering functionality  -----
 //
 
-
 function applyFilter() {
   gKeyListView.applyFilter(0);
 }
 
 function enigmailToggleShowAll() {
   EnigSetPref("keyManShowAllKeys", displayFullList());
 
   if (!gSearchInput.value || gSearchInput.value.length === 0) {
     gKeyListView.applyFilter(0);
   }
 }
 
-function determineHiddenKeys(keyObj, showInvalidKeys, showUntrustedKeys, showOthersKeys) {
+function determineHiddenKeys(
+  keyObj,
+  showInvalidKeys,
+  showUntrustedKeys,
+  showOthersKeys
+) {
   var show = true;
 
   const INVALID_KEYS = "ierdD";
   const UNTRUSTED_KEYS = "n-";
 
-  if ((!showInvalidKeys) && INVALID_KEYS.indexOf(EnigGetTrustCode(keyObj)) >= 0)
+  if (!showInvalidKeys && INVALID_KEYS.includes(EnigGetTrustCode(keyObj))) {
+    show = false;
+  }
+  if (!showUntrustedKeys && UNTRUSTED_KEYS.includes(keyObj.ownerTrust)) {
     show = false;
-  if ((!showUntrustedKeys) && UNTRUSTED_KEYS.indexOf(keyObj.ownerTrust) >= 0)
+  }
+  if (!showOthersKeys && !keyObj.secretAvailable) {
     show = false;
-  if ((!showOthersKeys) && (!keyObj.secretAvailable))
-    show = false;
+  }
 
   return show;
 }
 
 //
 // ----- keyserver related functionality ----
 //
 function accessKeyServer(accessType, callbackFunc) {
+  var enigmailSvc = GetEnigmailSvc();
+  if (!enigmailSvc) {
+    return;
+  }
 
-  var enigmailSvc = GetEnigmailSvc();
-  if (!enigmailSvc)
-    return;
-
-  const ioService = Cc[IOSERVICE_CONTRACTID].getService(Ci.nsIIOService);
+  const ioService = Services.io;
   if (ioService && ioService.offline) {
     EnigmailDialog.alert(window, EnigmailLocale.getString("needOnline"));
     return;
   }
 
   let inputObj = {};
   let resultObj = {};
   let selKeyList = getSelectedKeys();
   let keyList = [];
   for (let i = 0; i < selKeyList.length; i++) {
     keyList.push(gKeyList[selKeyList[i]]);
   }
 
   if (accessType !== EnigmailConstants.REFRESH_KEY && selKeyList.length === 0) {
-    if (EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("refreshAllQuestion"), EnigmailLocale.getString("keyMan.button.refreshAll"))) {
+    if (
+      EnigmailDialog.confirmDlg(
+        window,
+        EnigmailLocale.getString("refreshAllQuestion"),
+        EnigmailLocale.getString("keyMan.button.refreshAll")
+      )
+    ) {
       accessType = EnigmailConstants.DOWNLOAD_KEY;
-      EnigmailDialog.alertPref(window, EnigmailLocale.getString("refreshKey.warn"), "warnRefreshAll");
+      EnigmailDialog.alertPref(
+        window,
+        EnigmailLocale.getString("refreshKey.warn"),
+        "warnRefreshAll"
+      );
     } else {
       return;
     }
   }
 
-  let keyServer = EnigmailPrefs.getPref("autoKeyServerSelection") ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0] : null;
+  let keyServer = EnigmailPrefs.getPref("autoKeyServerSelection")
+    ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0]
+    : null;
   if (!keyServer) {
     switch (accessType) {
       case EnigmailConstants.REFRESH_KEY:
         inputObj.upload = false;
         inputObj.keyId = "All keys";
         break;
       case EnigmailConstants.DOWNLOAD_KEY:
         inputObj.upload = false;
-        inputObj.keyId = keyList.map(k => {
-          try {
-            return EnigmailFuncs.stripEmail(k.userId);
-          } catch (x) {
-            return "0x" + k.fpr;
-          }
-        }).join(", ");
+        inputObj.keyId = keyList
+          .map(k => {
+            try {
+              return EnigmailFuncs.stripEmail(k.userId);
+            } catch (x) {
+              return "0x" + k.fpr;
+            }
+          })
+          .join(", ");
         break;
       case EnigmailConstants.UPLOAD_KEY:
         inputObj.upload = true;
-        inputObj.keyId = keyList.map(k => {
-          try {
-            return EnigmailFuncs.stripEmail(k.userId);
-          } catch (x) {
-            return "0x" + k.fpr;
-          }
-        }).join(", ");
+        inputObj.keyId = keyList
+          .map(k => {
+            try {
+              return EnigmailFuncs.stripEmail(k.userId);
+            } catch (x) {
+              return "0x" + k.fpr;
+            }
+          })
+          .join(", ");
         break;
       default:
         inputObj.upload = true;
         inputObj.keyId = "";
     }
 
-    window.openDialog("chrome://openpgp/content/ui/enigmailKeyserverDlg.xhtml",
-      "", "dialog,modal,centerscreen", inputObj, resultObj);
+    window.openDialog(
+      "chrome://openpgp/content/ui/enigmailKeyserverDlg.xhtml",
+      "",
+      "dialog,modal,centerscreen",
+      inputObj,
+      resultObj
+    );
     keyServer = resultObj.value;
   }
 
-  if (keyServer.length === 0) return;
+  if (keyServer.length === 0) {
+    return;
+  }
 
   if (accessType !== EnigmailConstants.REFRESH_KEY) {
     inputObj.keyServer = keyServer;
     inputObj.accessType = accessType;
     inputObj.keyId = keyList.map(k => {
       return "0x" + k.fpr;
     });
-    window.openDialog("chrome://openpgp/content/ui/enigRetrieveProgress.xhtml",
-      "", "dialog,modal,centerscreen", inputObj, resultObj);
+    window.openDialog(
+      "chrome://openpgp/content/ui/enigRetrieveProgress.xhtml",
+      "",
+      "dialog,modal,centerscreen",
+      inputObj,
+      resultObj
+    );
 
     if (resultObj.result) {
       callbackFunc(resultObj.exitCode, resultObj.errorMsg, false);
     }
   } else {
     EnigmailKeyServer.refresh(keyServer);
   }
 }
 
 function getSortDirection() {
   return gUserList.getAttribute("sortDirection") == "ascending" ? 1 : -1;
 }
 
 function sortTree(column) {
-
   var columnName;
   var order = getSortDirection();
 
   //if the column is passed and it's already sorted by that column, reverse sort
   if (column) {
     columnName = column.id;
     if (gUserList.getAttribute("sortResource") == columnName) {
       order *= -1;
     } else {
-      document.getElementById(gUserList.getAttribute("sortResource")).removeAttribute("sortDirection");
+      document
+        .getElementById(gUserList.getAttribute("sortResource"))
+        .removeAttribute("sortDirection");
       order = 1;
     }
   } else {
     columnName = gUserList.getAttribute("sortResource");
   }
-  gUserList.setAttribute("sortDirection", order == 1 ? "ascending" : "descending");
+  gUserList.setAttribute(
+    "sortDirection",
+    order == 1 ? "ascending" : "descending"
+  );
   let col = document.getElementById(columnName);
   if (col) {
     col.setAttribute("sortDirection", order == 1 ? "ascending" : "descending");
     gUserList.setAttribute("sortResource", columnName);
   } else {
     gUserList.setAttribute("sortResource", "enigUserNameCol");
   }
   buildKeyList(false);
 }
 
-
 function getSortColumn() {
   switch (gUserList.getAttribute("sortResource")) {
     case "enigUserNameCol":
       return "userid";
     case "keyCol":
       return "keyid";
     case "typeCol":
       return "keytype";
@@ -1200,128 +1426,133 @@ var gKeyListView = {
   keyViewList: [],
   keyFilterList: [],
 
   //// nsITreeView implementation
 
   rowCount: 0,
   selection: null,
 
-  canDrop: function(index, orientation, dataTransfer) {
+  canDrop(index, orientation, dataTransfer) {
     return false;
   },
 
-  cycleCell: function(row, col) {},
-  cycleHeader: function(col) {},
-  drop: function(row, orientation, dataTransfer) {},
+  cycleCell(row, col) {},
+  cycleHeader(col) {},
+  drop(row, orientation, dataTransfer) {},
 
-  getCellProperties: function(row, col) {
+  getCellProperties(row, col) {
     let r = this.getFilteredRow(row);
-    if (!r) return "";
+    if (!r) {
+      return "";
+    }
 
     let keyObj = gKeyList[r.keyNum];
 
     let keyTrustStyle = "";
 
     switch (r.rowType) {
       case "key":
       case "uid":
       case "uat":
         switch (keyObj.keyTrust) {
-          case 'q':
+          case "q":
             keyTrustStyle = "enigmail_keyValid_unknown";
             break;
-          case 'i':
+          case "i":
             keyTrustStyle = "enigmail_keyValid_invalid";
             break;
-          case 'd':
+          case "d":
             keyTrustStyle = "enigmail_keyValid_disabled";
             break;
-          case 'r':
+          case "r":
             keyTrustStyle = "enigmail_keyValid_revoked";
             break;
-          case 'e':
+          case "e":
             keyTrustStyle = "enigmail_keyValid_expired";
             break;
-          case 'n':
+          case "n":
             keyTrustStyle = "enigmail_keyTrust_untrusted";
             break;
-          case 'm':
+          case "m":
             keyTrustStyle = "enigmail_keyTrust_marginal";
             break;
-          case 'f':
+          case "f":
             keyTrustStyle = "enigmail_keyTrust_full";
             break;
-          case 'u':
+          case "u":
             keyTrustStyle = "enigmail_keyTrust_ultimate";
             break;
-          case '-':
+          case "-":
             keyTrustStyle = "enigmail_keyTrust_unknown";
             break;
           default:
             keyTrustStyle = "enigmail_keyTrust_unknown";
             break;
         }
 
-        if (keyObj.keyUseFor.indexOf("D") >= 0) {
+        if (keyObj.keyUseFor.includes("D")) {
           keyTrustStyle = "enigmail_keyValid_disabled";
         }
 
-        if ((keyObj.keyTrust.length > 0) &&
-          (ENIG_KEY_NOT_VALID.indexOf(keyObj.keyTrust.charAt(0)) >= 0) ||
-          (keyObj.keyUseFor.indexOf("D") >= 0)) {
+        if (
+          (keyObj.keyTrust.length > 0 &&
+            ENIG_KEY_NOT_VALID.includes(keyObj.keyTrust.charAt(0))) ||
+          keyObj.keyUseFor.includes("D")
+        ) {
           keyTrustStyle += " enigKeyInactive";
         }
 
         if (r.rowType === "key" && keyObj.secretAvailable) {
           keyTrustStyle += " enigmailOwnKey";
         }
         break;
     }
 
     return keyTrustStyle;
   },
 
-  getCellText: function(row, col) {
-
+  getCellText(row, col) {
     let r = this.getFilteredRow(row);
-    if (!r) return "";
+    if (!r) {
+      return "";
+    }
     let keyObj = gKeyList[r.keyNum];
 
     switch (r.rowType) {
       case "key":
         switch (col.id) {
           case "enigUserNameCol":
             return keyObj.userId;
           case "keyCol":
             return keyObj.keyId;
           case "typeCol":
             if (keyObj.secretAvailable) {
               return EnigmailLocale.getString("keyType.publicAndSec");
             }
             return EnigmailLocale.getString("keyType.public");
           case "validityCol":
-            if (keyObj.keyUseFor.indexOf("D") >= 0) {
+            if (keyObj.keyUseFor.includes("D")) {
               return EnigmailLocale.getString("keyValid.disabled");
             }
             return EnigGetTrustLabel(keyObj.keyTrust);
           case "trustCol":
             return EnigGetTrustLabel(keyObj.ownerTrust);
           case "expCol":
             return keyObj.expiry;
           case "fprCol":
             return keyObj.fprFormatted;
         }
         break;
       case "uid":
         switch (col.id) {
           case "enigUserNameCol":
             return keyObj.userIds[r.uidNum].userId;
           case "validityCol":
-            if (keyObj.keyUseFor.indexOf("D") >= 0) {
+            if (keyObj.keyUseFor.includes("D") >= 0) {
               return EnigmailLocale.getString("keyValid.disabled");
             }
             return EnigGetTrustLabel(keyObj.userIds[r.uidNum].keyTrust);
           case "trustCol":
             return EnigGetTrustLabel(keyObj.ownerTrust);
         }
         break;
       case "uidHdr":
@@ -1348,37 +1579,41 @@ var gKeyListView = {
         if (col.id === "enigUserNameCol") {
           return EnigmailLocale.getString("keylist.noPhotos");
         }
         break;
     }
 
     return "";
   },
-  getCellValue: function(row, col) {
+  getCellValue(row, col) {
     return "";
   },
-  getColumnProperties: function(col) {
+  getColumnProperties(col) {
     return "";
   },
 
-  getImageSrc: function(row, col) {
+  getImageSrc(row, col) {
     let r = this.getFilteredRow(row);
-    if (!r) return null;
-    let keyObj = gKeyList[r.keyNum];
+    if (!r) {
+      return null;
+    }
+    //let keyObj = gKeyList[r.keyNum];
 
     return null;
   },
 
   /**
    * indentation level for rows
    */
-  getLevel: function(row) {
+  getLevel(row) {
     let r = this.getFilteredRow(row);
-    if (!r) return 0;
+    if (!r) {
+      return 0;
+    }
 
     switch (r.rowType) {
       case "key":
         return 0;
       case "uidHdr":
       case "noUidHdr":
       case "uatHdr":
       case "noUatHdr":
@@ -1386,98 +1621,117 @@ var gKeyListView = {
       case "uid":
       case "uat":
         return 2;
     }
 
     return 0;
   },
 
-  getParentIndex: function(idx) {
+  getParentIndex(idx) {
     return -1;
   },
-  getProgressMode: function(row, col) {},
+  getProgressMode(row, col) {},
 
-  getRowProperties: function(row) {
+  getRowProperties(row) {
     return "";
   },
   hasNextSibling(rowIndex, afterIndex) {
     return false;
   },
-  isContainer: function(row) {
+  isContainer(row) {
     let r = this.getFilteredRow(row);
-    if (!r) return false;
+    if (!r) {
+      return false;
+    }
     switch (r.rowType) {
       case "key":
         return true;
     }
 
     return false;
   },
-  isContainerEmpty: function(row) {
+  isContainerEmpty(row) {
     let r = this.getFilteredRow(row);
-    if (!r) return true;
+    if (!r) {
+      return true;
+    }
     switch (r.rowType) {
       case "key":
         return false;
       case "uidHdr":
         return r.isOpen;
     }
     return true;
   },
-  isContainerOpen: function(row) {
+  isContainerOpen(row) {
     return this.getFilteredRow(row).isOpen;
   },
-  isEditable: function(row, col) {
+  isEditable(row, col) {
     return false;
   },
-  isSelectable: function(row, col) {
+  isSelectable(row, col) {
     return true;
   },
-  isSeparator: function(index) {
+  isSeparator(index) {
     return false;
   },
-  isSorted: function() {
+  isSorted() {
     return false;
   },
-  performAction: function(action) {},
-  performActionOnCell: function(action, row, col) {},
-  performActionOnRow: function(action, row) {},
-  selectionChanged: function() {},
+  performAction(action) {},
+  performActionOnCell(action, row, col) {},
+  performActionOnRow(action, row) {},
+  selectionChanged() {},
   // void setCellText(in long row, in nsITreeColumn col, in AString value);
   // void setCellValue(in long row, in nsITreeColumn col, in AString value);
-  setTree: function(treebox) {
+  setTree(treebox) {
     this.treebox = treebox;
   },
 
-  toggleOpenState: function(row) {
+  toggleOpenState(row) {
     let r = this.getFilteredRow(row);
-    if (!r) return;
+    if (!r) {
+      return;
+    }
     let realRow = this.keyFilterList[row];
     switch (r.rowType) {
       case "key":
         if (r.isOpen) {
           let i = 0;
-          while (this.getFilteredRow(row + 1 + i) && this.getFilteredRow(row + 1 + i).keyNum === r.keyNum) {
+          while (
+            this.getFilteredRow(row + 1 + i) &&
+            this.getFilteredRow(row + 1 + i).keyNum === r.keyNum
+          ) {
             ++i;
           }
 
           this.keyViewList.splice(realRow + 1, i);
           r.isOpen = false;
           this.applyFilter(row);
         } else {
-          let numUid = this.appendUids("uid", r.keyNum, realRow, this.keyViewList[row]);
+          let numUid = this.appendUids(
+            "uid",
+            r.keyNum,
+            realRow,
+            this.keyViewList[row]
+          );
 
           if (numUid > 0) {
             this.appendHdr(realRow, "uidHdr", true);
           } else {
             this.appendHdr(realRow, "noUidHdr", false);
           }
 
-          let numPhoto = this.appendUids("uat", r.keyNum, realRow + numUid + 1, this.keyViewList[row]);
+          let numPhoto = this.appendUids(
+            "uat",
+            r.keyNum,
+            realRow + numUid + 1,
+            this.keyViewList[row]
+          );
 
           if (numPhoto > 0) {
             this.appendHdr(realRow + numUid + 1, "uatHdr", true);
           } else {
             this.appendHdr(realRow + numUid + 1, "noUatHdr", false);
           }
 
           r.isOpen = true;
@@ -1491,227 +1745,256 @@ var gKeyListView = {
    * add UIDs for a given key to key view
    *
    * @param uidType: String - one of uid (user ID), uat (photo)
    * @param keyNum:  Number - index of key in gKeyList
    * @param realRow: Number - index of row in keyViewList (i.e. without filter)
    *
    * @return Number: number of UIDs added
    */
-  appendUids: function(uidType, keyNum, realRow, parentRow) {
+  appendUids(uidType, keyNum, realRow, parentRow) {
     let keyObj = gKeyList[keyNum];
     let uidAdded = 0;
 
     for (let i = 1; i < keyObj.userIds.length; i++) {
       if (keyObj.userIds[i].type === uidType) {
         ++uidAdded;
         this.keyViewList.splice(realRow + uidAdded, 0, {
           rowType: uidType,
-          keyNum: keyNum,
+          keyNum,
           parent: parentRow,
-          uidNum: i
+          uidNum: i,
         });
       }
     }
 
     return uidAdded;
   },
 
   /**
    * add header row (e.g. "also known as") to tree view
    *
    * @param realRow:     Number - index of row in keyViewList (i.e. without filter)
    * @param headerType:  String - one of uid (user ID), uat (photo)
    * @param hasChildren: Boolean - whether or not there are rows underneath the header
    */
-  appendHdr: function(realRow, headerType, hasChildren) {
+  appendHdr(realRow, headerType, hasChildren) {
     let r = this.keyViewList[realRow];
     this.keyViewList.splice(realRow + 1, 0, {
       rowType: headerType,
       isOpen: hasChildren,
       keyNum: r.keyNum,
-      parent: this.keyViewList[realRow]
+      parent: this.keyViewList[realRow],
     });
   },
 
-
   /**
    * Reload key list entirely
    */
-  keysRefreshed: function() {
+  keysRefreshed() {
     this.keyViewList = [];
     this.keyFilterList = [];
     for (let i = 0; i < gKeySortList.length; i++) {
       this.keyViewList.push({
         row: i,
         rowType: "key",
         fpr: gKeySortList[i].fpr,
         keyNum: gKeySortList[i].keyNum,
-        isOpen: false
+        isOpen: false,
       });
     }
 
     this.applyFilter(0);
     let oldRowCount = this.rowCount;
     this.rowCount = this.keyViewList.length;
     gTreeFuncs.rowCountChanged(0, this.rowCount - oldRowCount);
   },
 
   /**
    * If no search term is entered, decide which keys to display
    *
    * @return array of keyNums (= display some keys) or null (= display ALL keys)
    */
-  showOrHideAllKeys: function() {
+  showOrHideAllKeys() {
     var hideNode = !displayFullList();
     var initHint = document.getElementById("emptyTree");
     var showInvalidKeys = gShowInvalidKeys.getAttribute("checked") == "true";
-    var showUntrustedKeys = gShowUntrustedKeys.getAttribute("checked") == "true";
+    var showUntrustedKeys =
+      gShowUntrustedKeys.getAttribute("checked") == "true";
     var showOthersKeys = gShowOthersKeys.getAttribute("checked") == "true";
 
     document.getElementById("nothingFound").hidePopup();
     if (hideNode) {
       initHint.showPopup(gTreeChildren, -1, -1, "tooltip", "after_end", "");
       return [];
-    } else {
-      initHint.hidePopup();
     }
+    initHint.hidePopup();
 
     if (showInvalidKeys && showUntrustedKeys && showOthersKeys) {
       return null;
     }
 
     let keyShowList = [];
     for (let i = 0; i < gKeyList.length; i++) {
-      if (determineHiddenKeys(gKeyList[i], showInvalidKeys, showUntrustedKeys, showOthersKeys)) {
+      if (
+        determineHiddenKeys(
+          gKeyList[i],
+          showInvalidKeys,
+          showUntrustedKeys,
+          showOthersKeys
+        )
+      ) {
         keyShowList.push(i);
       }
     }
 
     return keyShowList;
   },
 
   /**
    * Search for keys that match filter criteria
    *
    * @return array of keyNums (= display some keys) or null (= display ALL keys)
    */
-  getFilteredKeys: function() {
+  getFilteredKeys() {
     let searchTxt = gSearchInput.value;
 
     if (!searchTxt || searchTxt.length === 0) {
       return this.showOrHideAllKeys();
     }
 
-    if (!gKeyList) return [];
+    if (!gKeyList) {
+      return [];
+    }
     let showInvalidKeys = gShowInvalidKeys.getAttribute("checked") == "true";
-    let showUntrustedKeys = gShowUntrustedKeys.getAttribute("checked") == "true";
+    let showUntrustedKeys =
+      gShowUntrustedKeys.getAttribute("checked") == "true";
     let showOthersKeys = gShowOthersKeys.getAttribute("checked") == "true";
 
     document.getElementById("emptyTree").hidePopup();
 
     // skip leading 0x in case we search for a key:
     if (searchTxt.length > 2 && searchTxt.substr(0, 2).toLowerCase() == "0x") {
       searchTxt = searchTxt.substr(2);
     }
 
     searchTxt = searchTxt.toLowerCase();
     searchTxt = searchTxt.replace(/^(\s*)(.*)/, "$2").replace(/\s+$/, ""); // trim spaces
 
     // check if we search for a full fingerprint (with optional spaces every 4 letters)
     var fpr = null;
-    if (searchTxt.length == 49) { // possible fingerprint with spaces?
-      if (searchTxt.search(/^[0-9a-f ]*$/) >= 0 && searchTxt[4] == ' ' && searchTxt[9] == ' ' && searchTxt[14] == ' ' &&
-        searchTxt[19] == ' ' && searchTxt[24] == ' ' && searchTxt[29] == ' ' &&
-        searchTxt[34] == ' ' && searchTxt[39] == ' ' && searchTxt[44] == ' ') {
+    if (searchTxt.length == 49) {
+      // possible fingerprint with spaces?
+      if (
+        searchTxt.search(/^[0-9a-f ]*$/) >= 0 &&
+        searchTxt[4] == " " &&
+        searchTxt[9] == " " &&
+        searchTxt[14] == " " &&
+        searchTxt[19] == " " &&
+        searchTxt[24] == " " &&
+        searchTxt[29] == " " &&
+        searchTxt[34] == " " &&
+        searchTxt[39] == " " &&
+        searchTxt[44] == " "
+      ) {
         fpr = searchTxt.replace(/ /g, "");
       }
-    } else if (searchTxt.length == 40) { // possible fingerprint without spaces
+    } else if (searchTxt.length == 40) {
+      // possible fingerprint without spaces
       if (searchTxt.search(/^[0-9a-f ]*$/) >= 0) {
         fpr = searchTxt;
       }
     }
 
-    let foundResult = false;
     let keyShowList = [];
 
     for (let i = 0; i < gKeyList.length; i++) {
       let keyObj = gKeyList[i];
       let uid = keyObj.userId;
       let showKey = false;
 
       // does a user ID (partially) match?
       for (let idx = 0; idx < keyObj.userIds.length; idx++) {
         uid = keyObj.userIds[idx].userId;
-        if (uid.toLowerCase().indexOf(searchTxt) >= 0) {
+        if (uid.toLowerCase().includes(searchTxt)) {
           showKey = true;
         }
       }
 
       // does the full fingerprint (without spaces) match?
       // - no partial match check because this is special for the collapsed spaces inside the fingerprint
       if (showKey === false && fpr && keyObj.fpr.toLowerCase() == fpr) {
         showKey = true;
       }
       // does the fingerprint (partially) match?
-      if (showKey === false && keyObj.fpr.toLowerCase().indexOf(searchTxt) >= 0) {
+      if (showKey === false && keyObj.fpr.toLowerCase().includes(searchTxt)) {
         showKey = true;
       }
       // does a sub key of (partially) match?
       if (showKey === false) {
-        for (let subKeyIdx = 0; subKeyIdx < keyObj.subKeys.length; subKeyIdx++) {
+        for (
+          let subKeyIdx = 0;
+          subKeyIdx < keyObj.subKeys.length;
+          subKeyIdx++
+        ) {
           let subkey = keyObj.subKeys[subKeyIdx].keyId;
-          if (subkey.toLowerCase().indexOf(searchTxt) >= 0) {
+          if (subkey.toLowerCase().includes(searchTxt)) {
             showKey = true;
           }
         }
       }
       // take option to show invalid/untrusted... keys into account
-      let hideKey = true;
-      if (showKey && determineHiddenKeys(keyObj, showInvalidKeys, showUntrustedKeys, showOthersKeys)) {
+      if (
+        showKey &&
+        determineHiddenKeys(
+          keyObj,
+          showInvalidKeys,
+          showUntrustedKeys,
+          showOthersKeys
+        )
+      ) {
         keyShowList.push(i);
-        foundResult = true;
       }
     }
 
     return keyShowList;
   },
 
   /**
    * Trigger re-displaying the list of keys and apply a filter
    *
    * @param selectedRow: Number - the row that is currently selected or
    *                     clicked on
    */
-  applyFilter: function(selectedRow) {
+  applyFilter(selectedRow) {
     let keyDisplayList = this.getFilteredKeys();
 
     this.keyFilterList = [];
     if (keyDisplayList === null) {
       for (let i = 0; i < this.keyViewList.length; i++) {
         this.keyFilterList.push(i);
       }
 
       this.adjustRowCount(this.keyViewList.length, selectedRow);
     } else {
       for (let i = 0; i < this.keyViewList.length; i++) {
-        if (keyDisplayList.indexOf(this.keyViewList[i].keyNum) >= 0) {
+        if (keyDisplayList.includes(this.keyViewList[i].keyNum)) {
           this.keyFilterList.push(i);
         }
       }
 
       this.adjustRowCount(this.keyFilterList.length, selectedRow);
     }
   },
 
   /**
    * Re-calculate the row count and instruct the view to update
    */
 
-  adjustRowCount: function(newRowCount, selectedRow) {
+  adjustRowCount(newRowCount, selectedRow) {
     if (this.rowCount === newRowCount) {
       gTreeFuncs.invalidate();
       return;
     }
 
     let delta = newRowCount - this.rowCount;
     this.rowCount = newRowCount;
     gTreeFuncs.rowCountChanged(selectedRow, delta);
@@ -1720,18 +2003,18 @@ var gKeyListView = {
   /**
    * Determine the row object from the a filtered row number
    *
    * @param row: Number - row number of displayed (=filtered) list
    *
    * @return Object: keyViewList entry of corresponding row
    */
 
-  getFilteredRow: function(row) {
+  getFilteredRow(row) {
     let r = this.keyFilterList[row];
     if (r !== undefined) {
       return this.keyViewList[r];
     }
     return null;
   },
 
-  treebox: null
+  treebox: null,
 };
--- a/mail/extensions/openpgp/content/ui/enigmailKeySelection.js
+++ b/mail/extensions/openpgp/content/ui/enigmailKeySelection.js
@@ -3,32 +3,39 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 // Uses: chrome://openpgp/content/ui/enigmailCommon.js
 
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
 /* global EnigInitCommon: false, EnigmailTrust: false, EnigGetString: false, EnigmailCore: false, EnigmailLog: false */
 /* global EnigmailKeyRing: false, EnigGetPref: false, EnigGetTrustLabel: false, EnigSetActive: false, EnigAlert: false */
 /* global EnigSetPref: false, EnigConfirm: false, EnigmailPrefs: false, EnigDownloadKeys: false */
 
 // Initialize enigmailCommon
 EnigInitCommon("enigmailKeySelection");
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-var EnigmailSearchCallback = ChromeUtils.import("chrome://openpgp/content/modules/searchCallback.jsm").EnigmailSearchCallback;
-var EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
-var newEnigmailKeyObj = ChromeUtils.import("chrome://openpgp/content/modules/keyObj.jsm").newEnigmailKeyObj;
-var EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm")
+  .EnigmailKey;
+var EnigmailSearchCallback = ChromeUtils.import(
+  "chrome://openpgp/content/modules/searchCallback.jsm"
+).EnigmailSearchCallback;
+var EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
+var newEnigmailKeyObj = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyObj.jsm"
+).newEnigmailKeyObj;
+var EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
 var getCellAt = null;
 
 const INPUT = 0;
 const RESULT = 1;
 
 // field ID's of key list (as described in the doc/DETAILS file in the GnuPG distribution)
 const KEY_TRUST = 1;
 const KEY_ID = 4;
@@ -63,69 +70,76 @@ var gTimeoutId = {};
 var gEnigRemoveListener = false;
 var gKeysNotFound = [];
 const EMPTY_UID = " -";
 
 function onLoad() {
   EnigmailLog.DEBUG("enigmailKeySelection.js: onLoad\n");
 
   gIpcRequest = null;
-  if (window.arguments[INPUT].options.indexOf("private") >= 0) {
-    document.getElementById("enigmailKeySelectionDlg").setAttribute("title", EnigGetString("userSel.secretKeySel.title"));
+  if (window.arguments[INPUT].options.includes("private")) {
+    document
+      .getElementById("enigmailKeySelectionDlg")
+      .setAttribute("title", EnigGetString("userSel.secretKeySel.title"));
   }
 
   let tree = document.getElementById("enigmailUserIdSelection");
   getCellAt = EnigmailCompat.getTreeCompatibleFuncs(tree, null).getCellAt;
-  tree.addEventListener('click', onClickCallback, true);
-  EnigmailSearchCallback.setup(document.getElementById("filterKey"), gTimeoutId, applyFilter, 200);
+  tree.addEventListener("click", onClickCallback, true);
+  EnigmailSearchCallback.setup(
+    document.getElementById("filterKey"),
+    gTimeoutId,
+    applyFilter,
+    200
+  );
 
   let enigmailSvc = EnigmailCore.getService(window);
   if (!enigmailSvc) {
     return false;
   }
   buildList(false);
 
   return true;
 }
 
-
 function refreshKeys() {
   // delete existing entries:
   var userTreeList = document.getElementById("enigmailUserIdSelection");
-  var treeChildren = userTreeList.getElementsByAttribute("id", "enigmailUserIdSelectionChildren")[0];
+  var treeChildren = userTreeList.getElementsByAttribute(
+    "id",
+    "enigmailUserIdSelectionChildren"
+  )[0];
   while (treeChildren.firstChild) {
-    treeChildren.removeChild(treeChildren.firstChild);
+    treeChildren.firstChild.remove();
   }
   // rebuild new entries:
   buildList(true);
 }
 
-
 function getKeyList(secretOnly, refresh) {
   EnigmailLog.DEBUG("enigmailMessengerOverlay.js: getKeyList\n");
 
-  const cApi = EnigmailCryptoAPI();
-  let userList,
-    keyList;
+  //const cApi = EnigmailCryptoAPI();
+  let userList, keyList;
   try {
-    var exitCodeObj = {};
-    var statusFlagsObj = {};
-    var errorMsgObj = {};
-
     if (refresh) {
       EnigmailKeyRing.clearCache();
     }
 
     if (secretOnly) {
       userList = EnigmailKeyRing.getAllSecretKeys(window);
-      if (!userList) return null;
+      if (!userList) {
+        return null;
+      }
       keyList = EnigmailFuncs.cloneObj(userList);
     } else {
       userList = EnigmailKeyRing.getAllKeys(window);
-      if (!userList) return null;
+      if (!userList) {
+        return null;
+      }
 
       if (userList.trustModel === "t") {
         gAlwaysTrust = true;
       }
 
       keyList = EnigmailFuncs.cloneObj(userList.keyList);
     }
   } catch (ex) {
@@ -142,46 +156,57 @@ function getKeyList(secretOnly, refresh)
 function sortKeys(a, b) {
   // sorting criterion for dialog entries
   // - note: for active state we have values:
   //         0: not active
   //         1: active
   //         2: not selectable (red because invalid)
   var r = 0;
   // 1st: sort active keys in front of not active keys
-  if ((a.activeState != b.activeState) && (a.activeState == 1 || b.activeState == 1)) {
-    r = (a.activeState == 1 ? -1 : 1);
+  if (
+    a.activeState != b.activeState &&
+    (a.activeState == 1 || b.activeState == 1)
+  ) {
+    r = a.activeState == 1 ? -1 : 1;
   }
   // 2nd: sort keys matching invalid addresses in front non-matching addresses
   else if (a.uidMatchInvalid != b.uidMatchInvalid) {
-    r = (a.uidMatchInvalid == 1 ? -1 : 1);
+    r = a.uidMatchInvalid == 1 ? -1 : 1;
   }
   // 3rd: sort non-activateable keys to the end
-  else if ((a.activeState != b.activeState) && (a.activeState == 2 || b.activeState == 2)) {
-    r = (a.activeState === 0 ? -1 : 1);
+  else if (
+    a.activeState != b.activeState &&
+    (a.activeState == 2 || b.activeState == 2)
+  ) {
+    r = a.activeState === 0 ? -1 : 1;
   }
   // 4th: sort according to user IDs
   else if (a.userId.toLowerCase() < b.userId.toLowerCase()) {
     r = -1;
   } else if (a.userId.toLowerCase() > b.userId.toLowerCase()) {
     r = 1;
   }
   // 5th: sort according to trust level (higher index value in front)
-  else if (TRUSTLEVELS_SORTED.indexOf(a.keyTrust) > TRUSTLEVELS_SORTED.indexOf(b.keyTrust)) {
+  else if (
+    TRUSTLEVELS_SORTED.indexOf(a.keyTrust) >
+    TRUSTLEVELS_SORTED.indexOf(b.keyTrust)
+  ) {
     r = -1;
   } else {
     r = 1;
   }
   return r;
 }
 
 /**
  * Set up the dialog in terms of visible columns and top-level message(s)
  */
 function prepareDialog(secretOnly) {
+  throw new Error("Not implemented");
+  /*
   if (window.arguments[INPUT].dialogHeader) {
     var dialogHeader = document.getElementById("dialogHeader");
     if (dialogHeader) {
       dialogHeader.innerHTML = window.arguments[INPUT].dialogHeader;
       dialogHeader.style.visibility = "visible";
     }
   } else {
     let box = document.getElementById("dialogHeaderBox");
@@ -192,157 +217,186 @@ function prepareDialog(secretOnly) {
   var dialogMsgListRows = document.getElementById("dialogMsgListRows");
   if (dialogMsgListRows) {
     // clear the list (otherwise it grows with each loaded missing key)
     while (dialogMsgListRows.firstChild) {
       dialogMsgListRows.removeChild(dialogMsgListRows.firstChild);
     }
 
     // fill the list according to the error messages
-    if (window.arguments[INPUT].errArray && window.arguments[INPUT].errArray.length > 0) {
+    if (
+      window.arguments[INPUT].errArray &&
+      window.arguments[INPUT].errArray.length > 0
+    ) {
       var array = window.arguments[INPUT].errArray;
       for (var detIdx = 0; detIdx < array.length; ++detIdx) {
         var msg = null;
         switch (array[detIdx].msg) {
           case "ProblemNoKey":
             msg = EnigGetString("userSel.problemNoKey");
-            if (window.arguments[INPUT].options.indexOf("nosending") < 0) {
-              document.getElementById("importMissingKeys").removeAttribute("collapsed");
+            if (!window.arguments[INPUT].options.includes("nosending")) {
+              document
+                .getElementById("importMissingKeys")
+                .removeAttribute("collapsed");
             }
             break;
           case "ProblemMultipleKeys":
             msg = EnigGetString("userSel.problemMultipleKeys");
             break;
           default:
-            EnigmailLog.DEBUG("missing label for '" + array[detIdx].msg + "'\n");
+            EnigmailLog.DEBUG(
+              "missing label for '" + array[detIdx].msg + "'\n"
+            );
             msg = "???";
             break;
         }
-        var row = document.createXULElement('row');
-        var cell = document.createXULElement('label');
-        cell.setAttribute('value', array[detIdx].addr + ":");
+        var row = document.createXULElement("row");
+        var cell = document.createXULElement("label");
+        cell.setAttribute("value", array[detIdx].addr + ":");
         row.appendChild(cell);
-        cell = document.createXULElement('label');
-        cell.setAttribute('value', msg);
+        cell = document.createXULElement("label");
+        cell.setAttribute("value", msg);
         row.appendChild(cell);
         dialogMsgListRows.appendChild(row);
       }
       dialogMsgList.removeAttribute("collapsed");
     } else {
       dialogMsgList.setAttribute("collapsed", "true");
     }
   }
 
   if (secretOnly) {
     // rename expired row to created
-    document.getElementById("expCol").setAttribute("label", EnigGetString("createdHeader"));
+    document
+      .getElementById("expCol")
+      .setAttribute("label", EnigGetString("createdHeader"));
   }
 
-  if (window.arguments[INPUT].options.indexOf("unsigned") >= 0) {
+  if (window.arguments[INPUT].options.includes("unsigned")) {
     gSendSigned = false;
-    var sendSignedCheckbox = document.getElementById("enigmailUserSelSendSigned");
+    var sendSignedCheckbox = document.getElementById(
+      "enigmailUserSelSendSigned"
+    );
     sendSignedCheckbox.setAttribute("checked", "false");
   }
-  if ((window.arguments[INPUT].options.indexOf("rulesOption") < 0)) {
-    var rulesOption = document.getElementById("enigmailKeySelectionDlg").getButton("extra1");
+  if (!window.arguments[INPUT].options.includes("rulesOption")) {
+    var rulesOption = document
+      .getElementById("enigmailKeySelectionDlg")
+      .getButton("extra1");
     rulesOption.setAttribute("hidden", "true");
   }
 
   var dialogHeaderDesc = document.getElementById("dialogHeaderDesc");
   var notFoundCapt = document.getElementById("usersNotFoundCapt");
 
-  if (window.arguments[INPUT].options.indexOf("multisel") < 0) {
+  if (!window.arguments[INPUT].options.includes("multisel")) {
     // single key selection -> hide selection col
     var selColumn = document.getElementById("selectionCol");
     selColumn.setAttribute("collapsed", "true");
     gUserList.setAttribute("hidecolumnpicker", "true");
   }
 
-  if (window.arguments[INPUT].options.indexOf("nosending") >= 0) {
+  if (window.arguments[INPUT].options.includes("nosending")) {
     // hide not found recipients, hide "send unencrypted"
     document.getElementById("dialogHeadline").setAttribute("collapsed", "true");
-    document.getElementById("enigmailUserSelSendSigned").setAttribute("collapsed", "true");
-    document.getElementById("enigmailUserSelSendEncrypted").setAttribute("collapsed", "true");
-  } else if (window.arguments[INPUT].options.indexOf("noforcedisp") >= 0) {
+    document
+      .getElementById("enigmailUserSelSendSigned")
+      .setAttribute("collapsed", "true");
+    document
+      .getElementById("enigmailUserSelSendEncrypted")
+      .setAttribute("collapsed", "true");
+  } else if (window.arguments[INPUT].options.includes("noforcedisp")) {
     document.getElementById("displayNoLonger").removeAttribute("collapsed");
   }
 
-  if (window.arguments[INPUT].options.indexOf("noplaintext") >= 0) {
+  if (window.arguments[INPUT].options.includes("noplaintext")) {
     // hide "send unencrypted"
-    document.getElementById("enigmailUserSelSendEncrypted").setAttribute("collapsed", "true");
+    document
+      .getElementById("enigmailUserSelSendEncrypted")
+      .setAttribute("collapsed", "true");
   }
 
-  if (window.arguments[INPUT].options.indexOf("forUser") >= 0) {
+  if (window.arguments[INPUT].options.includes("forUser")) {
     // display title message for Per-Recipient Rule
-    dialogHeaderDesc.firstChild.data = EnigGetString("keysToUse", window.arguments[INPUT].forUser);
+    dialogHeaderDesc.firstChild.data = EnigGetString(
+      "keysToUse",
+      window.arguments[INPUT].forUser
+    );
     dialogHeaderDesc.removeAttribute("collapsed");
     notFoundCapt.setAttribute("collapsed", "true");
   }
 
-  if (window.arguments[INPUT].options.indexOf(",sendlabel=") >= 0) {
+  if (window.arguments[INPUT].options.includes(",sendlabel=")) {
     var pos1 = window.arguments[INPUT].options.indexOf(",sendlabel=");
     pos1 = window.arguments[INPUT].options.indexOf("=", pos1);
     var pos2 = window.arguments[INPUT].options.indexOf(",", pos1);
-    var acceptButton = document.getElementById("enigmailKeySelectionDlg").getButton("accept");
-    acceptButton.setAttribute("label", window.arguments[INPUT].options.substring(pos1 + 1, pos2));
+    var acceptButton = document
+      .getElementById("enigmailKeySelectionDlg")
+      .getButton("accept");
+    acceptButton.setAttribute(
+      "label",
+      window.arguments[INPUT].options.substring(pos1 + 1, pos2)
+    );
   }
+  */
 }
 
 function buildList(refresh) {
   EnigmailLog.DEBUG("enigmailKeySelection.js: buildList\n");
 
   window.arguments[RESULT].cancelled = true;
 
-  gAlwaysTrust = (EnigGetPref("acceptedKeys") == 1);
+  gAlwaysTrust = EnigGetPref("acceptedKeys") == 1;
 
-  var secretOnly = (window.arguments[INPUT].options.indexOf("private") >= 0);
-  var hideExpired = (window.arguments[INPUT].options.indexOf("hidexpired") >= 0);
-  gAllowExpired = (window.arguments[INPUT].options.indexOf("allowexpired") >= 0);
+  var secretOnly = window.arguments[INPUT].options.includes("private");
+  var hideExpired = window.arguments[INPUT].options.includes("hidexpired");
+  gAllowExpired = window.arguments[INPUT].options.includes("allowexpired");
 
-  if (window.arguments[INPUT].options.indexOf("trustallkeys") >= 0) {
+  if (window.arguments[INPUT].options.includes("trustallkeys")) {
     gAlwaysTrust = true;
   }
 
   var aUserList = getKeyList(secretOnly, refresh);
 
-  if (!aUserList) return;
+  if (!aUserList) {
+    return;
+  }
   var uidNotValid;
   if (gAlwaysTrust) {
     uidNotValid = "";
   } else {
     uidNotValid = "o-qn";
   }
 
   gUserList = document.getElementById("enigmailUserIdSelection");
   gUserList.currentItem = null;
 
   try {
     prepareDialog(secretOnly);
   } catch (ex) {
     EnigmailLog.DEBUG("EXCEPTION: " + ex.toString() + "\n");
   }
 
-
   var i;
   var j;
   var toKeys = "";
   try {
-    if (typeof(window.arguments[INPUT].toKeys) == "string") {
+    if (typeof window.arguments[INPUT].toKeys == "string") {
       toKeys = window.arguments[INPUT].toKeys;
     }
   } catch (ex) {}
 
   var invalidAddr = "";
   try {
     // the test below had "&& !refresh" probably not to list invalid keys
     // anymore after refreshing.
     // However, that's confusing because with the after refreshing keys
     // with no change in the key set, different items are selected.
     // Thus, this is disabled until there is a reprocessing of validity.
-    if (typeof(window.arguments[INPUT].invalidAddr) == "string") {
+    if (typeof window.arguments[INPUT].invalidAddr == "string") {
       invalidAddr = " " + window.arguments[INPUT].invalidAddr + " ";
     }
   } catch (ex) {}
 
   // sort out PGP keys in toAddr
   var toAddrList = getToAddrList();
   for (i = 0; i < toAddrList.length; i++) {
     if (toAddrList[i].search(/^0x([0-9A-Fa-f]{8}|[0-9A-Fa-f]{16})$/) >= 0) {
@@ -352,142 +406,165 @@ function buildList(refresh) {
     }
   }
   var toAddr = "<" + toAddrList.join("><") + ">";
 
   var d = new Date();
   var now = d.valueOf() / 1000;
   var aValidUsers = [];
 
-  var mailAddr,
-    escapedMailAddr;
+  var mailAddr, escapedMailAddr;
   var s1;
   // Replace any non-text character c with \\c
   var escapeRegExp = new RegExp("([^a-zA-Z0-9])", "g");
 
   // delete "empty" entries
   for (i = 0; i < aUserList.length; i++) {
-    if (typeof(aUserList[i].userId) != "string") {
+    if (typeof aUserList[i].userId != "string") {
       aUserList.splice(i, 1);
     }
   }
 
   let user;
 
   // find and activate keys
   try {
     for (i = 0; i < aUserList.length; i++) {
-
       // prepare key obj
-      if (aUserList[i].keyUseFor.indexOf("D") >= 0) {
+      if (aUserList[i].keyUseFor.includes("D")) {
         aUserList[i].keyTrust = KEY_DISABLED;
       }
-      aUserList[i].subkeyOK = (aUserList[i].keyUseFor.indexOf("e") >= 0 || secretOnly);
+      aUserList[i].subkeyOK =
+        aUserList[i].keyUseFor.includes("e") || secretOnly;
       aUserList[i].valid = false;
       aUserList[i].uidValid = true;
       aUserList[i].uidMatchInvalid = false; // by default don't match list of invalid emails
 
       if (aUserList[i].type === "grp") {
         // groups
         aUserList[i].valid = true;
         aUserList[i].uidValid = true;
         aUserList[i].subkeyOK = true;
       }
 
       for (let s in aUserList[i].subKeys) {
-        if ((aUserList[i].subKeys[s].keyUseFor.indexOf("e") >= 0) &&
-          (KEY_NOT_VALID.indexOf(aUserList[i].subKeys[s].keyTrust) < 0)) {
+        if (
+          aUserList[i].subKeys[s].keyUseFor.includes("e") &&
+          !KEY_NOT_VALID.includes(aUserList[i].subKeys[s].keyTrust)
+        ) {
           aUserList[i].subkeyOK = true;
         }
       }
 
       // work on key obj
 
       var toKeyList = toKeys.split(/[, ]+/);
 
-      aUserList[i].activeState = (gAllowExpired ? 0 : 2); // default: not activated/activateable
+      aUserList[i].activeState = gAllowExpired ? 0 : 2; // default: not activated/activateable
       if (aUserList[i].keyTrust != KEY_IS_GROUP) {
         // handling of "normal" keys
 
         mailAddr = stripEmailFromKey(aUserList[i].userId);
 
-        if (mailAddr != EMPTY_UID && invalidAddr.indexOf(" " + mailAddr + " ") >= 0) {
+        if (
+          mailAddr != EMPTY_UID &&
+          invalidAddr.includes(" " + mailAddr + " ")
+        ) {
           aUserList[i].uidMatchInvalid = true; // found matching but invalid email
         }
-        if (((!aUserList[i].keyTrust) ||
-            KEY_NOT_VALID.indexOf(aUserList[i].keyTrust) < 0) &&
+        if (
+          (!aUserList[i].keyTrust ||
+            !KEY_NOT_VALID.includes(aUserList[i].keyTrust)) &&
           aUserList[i].subkeyOK &&
-          (aUserList[i].expiryTime <= 0 ||
-            (aUserList[i].expiryTime >= now))) {
+          (aUserList[i].expiryTime <= 0 || aUserList[i].expiryTime >= now)
+        ) {
           // key still valid
           aUserList[i].valid = true;
           escapedMailAddr = mailAddr.replace(escapeRegExp, "\\$1");
 
           s1 = new RegExp("<" + escapedMailAddr + ">", "i");
           if (mailAddr != EMPTY_UID) {
-            if (invalidAddr.indexOf(" " + mailAddr + " ") < 0) {
+            if (!invalidAddr.includes(" " + mailAddr + " ")) {
               aValidUsers.push(mailAddr);
-              aUserList[i].activeState = (toAddr.search(s1) >= 0 ? 1 : 0);
+              aUserList[i].activeState = toAddr.search(s1) >= 0 ? 1 : 0;
             } else {
               // mail address found as invalid address: marks that to sort them to the beginning
               aUserList[i].uidMatchInvalid = true;
               aUserList[i].uidValid = false;
               aUserList[i].activeState = 0;
             }
           } else {
             aUserList[i].uidValid = false;
             aUserList[i].activeState = 0;
           }
           if (aUserList[i].activeState === 0 && toKeys.length > 0) {
             // Now loop through toKeyList and search for matching keyIds
             for (j = 0; j < toKeyList.length; j++) {
               if (toKeyList[j].length > 0) {
-                if (EnigmailKey.compareKeyIds(aUserList[i].keyId, toKeyList[j])) {
+                if (
+                  EnigmailKey.compareKeyIds(aUserList[i].keyId, toKeyList[j])
+                ) {
                   aUserList[i].activeState = 1;
                 }
               }
             }
           }
         }
       } else {
         // special handling for gpg groups
         mailAddr = stripEmailFromKey(aUserList[i].userId);
         aValidUsers.push(mailAddr);
         aUserList[i].valid = true;
         aUserList[i].uidValid = true;
         if (toKeys.length > 0) {
-          aUserList[i].activeState = (toKeys.indexOf("GROUP:" + aUserList[i].keyId + ",") >= 0 ? 1 : 0);
-        } else
+          aUserList[i].activeState = toKeys.includes(
+            "GROUP:" + aUserList[i].keyId + ","
+          )
+            ? 1
+            : 0;
+        } else {
           aUserList[i].activeState = 0;
+        }
       }
 
       if (!hideExpired || aUserList[i].activeState < 2) {
-        if ((aUserList[i].keyTrust != KEY_IS_GROUP) && aUserList[i].hasSubUserIds()) {
+        if (
+          aUserList[i].keyTrust != KEY_IS_GROUP &&
+          aUserList[i].hasSubUserIds()
+        ) {
           for (user = 1; user < aUserList[i].userIds.length; user++) {
-            if (KEY_NOT_VALID.indexOf(aUserList[i].userIds[user].keyTrust) < 0) {
+            if (!KEY_NOT_VALID.includes(aUserList[i].userIds[user].keyTrust)) {
               if (aUserList[i].activeState < 2 || gAllowExpired) {
                 // add uid's for valid keys
                 mailAddr = stripEmailFromKey(aUserList[i].userIds[user].userId);
-                if (uidNotValid.indexOf(aUserList[i].userIds[user].keyTrust) < 0) {
+                if (
+                  !uidNotValid.includes(aUserList[i].userIds[user].keyTrust)
+                ) {
                   aValidUsers.push(mailAddr);
                   aUserList[i].valid = true;
                   escapedMailAddr = mailAddr.replace(escapeRegExp, "\\$1");
                   s1 = new RegExp("<" + escapedMailAddr + ">", "i");
-                  if ((mailAddr != EMPTY_UID) && (toAddr.search(s1) >= 0)) {
+                  if (mailAddr != EMPTY_UID && toAddr.search(s1) >= 0) {
                     aUserList[i].activeState = 1;
                   }
                 }
               }
             }
           }
         }
       }
     }
   } catch (ex) {
-    EnigmailLog.ERROR("enigmailKeySelection.js: ERROR in buildList: " + ex.toString() + "\n" + ex.stack + "\n");
+    EnigmailLog.ERROR(
+      "enigmailKeySelection.js: ERROR in buildList: " +
+        ex.toString() +
+        "\n" +
+        ex.stack +
+        "\n"
+    );
   }
 
   // sort items according to sorting criterion
   aUserList.sort(sortKeys);
   buildTreeView(aUserList, hideExpired, secretOnly);
   buildNotFoundKeys(aUserList, aValidUsers, toAddrList, toKeys);
 
   EnigmailLog.DEBUG("  <=== buildList()\n");
@@ -495,32 +572,59 @@ function buildList(refresh) {
 
 /**
  * Build up tree view for displaying keys
  */
 function buildTreeView(aUserList, hideExpired, secretOnly) {
   EnigmailLog.DEBUG("enigmailKeySelection.js: buildTreeView\n");
 
   let i;
-  let treeChildren = gUserList.getElementsByAttribute("id", "enigmailUserIdSelectionChildren")[0];
+  let treeChildren = gUserList.getElementsByAttribute(
+    "id",
+    "enigmailUserIdSelectionChildren"
+  )[0];
 
   for (i = 0; i < aUserList.length; i++) {
     var treeItem = null;
     if (!hideExpired || aUserList[i].activeState < 2) {
       // do not show if expired keys are hidden
       if (secretOnly) {
-        treeItem = enigUserSelCreateRow(aUserList[i], aUserList[i].activeState, aUserList[i].userId, aUserList[i].keyId, aUserList[i].created, "", true);
+        treeItem = enigUserSelCreateRow(
+          aUserList[i],
+          aUserList[i].activeState,
+          aUserList[i].userId,
+          aUserList[i].keyId,
+          aUserList[i].created,
+          "",
+          true
+        );
       } else {
-        treeItem = enigUserSelCreateRow(aUserList[i], aUserList[i].activeState, aUserList[i].userId, aUserList[i].keyId, aUserList[i].expiry, aUserList[i].keyTrust, aUserList[i].uidValid);
+        treeItem = enigUserSelCreateRow(
+          aUserList[i],
+          aUserList[i].activeState,
+          aUserList[i].userId,
+          aUserList[i].keyId,
+          aUserList[i].expiry,
+          aUserList[i].keyTrust,
+          aUserList[i].uidValid
+        );
       }
       if (aUserList[i].hasSubUserIds()) {
         var subChildren = document.createXULElement("treechildren");
         for (let user = 1; user < aUserList[i].userIds.length; user++) {
-          if (KEY_NOT_VALID.indexOf(aUserList[i].userIds[user].keyTrust) < 0) {
-            var subItem = enigUserSelCreateRow(aUserList[i], -1, aUserList[i].userIds[user].userId, "", "", aUserList[i].userIds[user].keyTrust, true);
+          if (!KEY_NOT_VALID.includes(aUserList[i].userIds[user].keyTrust)) {
+            var subItem = enigUserSelCreateRow(
+              aUserList[i],
+              -1,
+              aUserList[i].userIds[user].userId,
+              "",
+              "",
+              aUserList[i].userIds[user].keyTrust,
+              true
+            );
             subChildren.appendChild(subItem);
           }
         }
         if (subChildren.hasChildNodes()) {
           treeItem.setAttribute("container", "true");
           treeItem.appendChild(subChildren);
         }
       }
@@ -534,57 +638,91 @@ function buildTreeView(aUserList, hideEx
 /**
  * Build up list of not found recipients
  */
 
 function buildNotFoundKeys(aUserList, aValidUsers, toAddrList, toKeys) {
   EnigmailLog.DEBUG("enigmailKeySelection.js: buildNotFoundKeys\n");
 
   gKeysNotFound = [];
-  let i,
-    j;
+  let i, j;
   for (i = 0; i < toAddrList.length; i++) {
     if (toAddrList[i].length > 0) {
       let found = false;
       for (j = 0; j < aValidUsers.length; j++) {
-        EnigmailLog.DEBUG("enigmailKeySelection.js: buildNotFoundKeys: comparing aValidUsers member " + aValidUsers[j].toLowerCase() + " and toAddrList member " + toAddrList[i].toLowerCase() + "\n");
+        EnigmailLog.DEBUG(
+          "enigmailKeySelection.js: buildNotFoundKeys: comparing aValidUsers member " +
+            aValidUsers[j].toLowerCase() +
+            " and toAddrList member " +
+            toAddrList[i].toLowerCase() +
+            "\n"
+        );
         if (aValidUsers[j].toLowerCase() == toAddrList[i].toLowerCase()) {
-          EnigmailLog.DEBUG("enigmailKeySelection.js: buildNotFoundKeys: aValidUsers member matches toAddrList member...\n");
+          EnigmailLog.DEBUG(
+            "enigmailKeySelection.js: buildNotFoundKeys: aValidUsers member matches toAddrList member...\n"
+          );
           found = true;
           break; // the inner loop
         }
       }
       if (!found) {
-        EnigmailLog.DEBUG("enigmailKeySelection.js: buildNotFoundKeys: not found " + toAddrList[i] + "\n");
+        EnigmailLog.DEBUG(
+          "enigmailKeySelection.js: buildNotFoundKeys: not found " +
+            toAddrList[i] +
+            "\n"
+        );
         gKeysNotFound.push(toAddrList[i]);
       }
     }
   }
   var toKeyList = toKeys.split(/[, ]+/);
   for (i = 0; i < toKeyList.length; i++) {
     if (toKeyList[i].length > 0) {
       let found = false;
       for (j = 0; j < aUserList.length; j++) {
-        EnigmailLog.DEBUG("enigmailKeySelection.js: buildNotFoundKeys: comparing toKeyList member " + toKeyList[i] + " and aUserList member 0x" + aUserList[j].keyId + "\n");
-        if (aUserList[j].valid && EnigmailKey.compareKeyIds(aUserList[j].keyId, toKeyList[i])) {
-          EnigmailLog.DEBUG("enigmailKeySelection.js: buildNotFoundKeys: aUserList member is valid and key Id matches...\n");
+        EnigmailLog.DEBUG(
+          "enigmailKeySelection.js: buildNotFoundKeys: comparing toKeyList member " +
+            toKeyList[i] +
+            " and aUserList member 0x" +
+            aUserList[j].keyId +
+            "\n"
+        );
+        if (
+          aUserList[j].valid &&
+          EnigmailKey.compareKeyIds(aUserList[j].keyId, toKeyList[i])
+        ) {
+          EnigmailLog.DEBUG(
+            "enigmailKeySelection.js: buildNotFoundKeys: aUserList member is valid and key Id matches...\n"
+          );
           found = true;
           break; // the inner loop
         }
       }
       if (!found) {
-        EnigmailLog.DEBUG("enigmailKeySelection.js: buildNotFoundKeys: not found " + toKeyList[i] + "\n");
+        EnigmailLog.DEBUG(
+          "enigmailKeySelection.js: buildNotFoundKeys: not found " +
+            toKeyList[i] +
+            "\n"
+        );
         gKeysNotFound.push(toKeyList[i]);
       }
     }
   }
 }
 
 // create a (sub) row for the user tree
-function enigUserSelCreateRow(userObj, activeState, userId, keyValue, dateField, uidValidityStatus, uidValid) {
+function enigUserSelCreateRow(
+  userObj,
+  activeState,
+  userId,
+  keyValue,
+  dateField,
+  uidValidityStatus,
+  uidValid
+) {
   var selectCol = document.createXULElement("treecell");
   selectCol.setAttribute("id", "indicator");
   var uidValidityCol = document.createXULElement("treecell");
   var expCol = document.createXULElement("treecell");
   var userCol = document.createXULElement("treecell");
 
   userCol.setAttribute("id", "name");
   expCol.setAttribute("id", "expiry");
@@ -600,39 +738,47 @@ function enigUserSelCreateRow(userObj, a
     keyCol.setAttribute("label", EnigGetString("keyTrust.group"));
   }
   keyCol.setAttribute("id", "keyid");
 
   // process validity label
   var validity = EnigGetTrustLabel(uidValidityStatus.charAt(0));
   if (!uidValid) {
     if (validity == "-") {
-      validity = "-  (" + EnigGetString("keyTrust.untrusted").toUpperCase() + ")";
+      validity =
+        "-  (" + EnigGetString("keyTrust.untrusted").toUpperCase() + ")";
     }
   }
-  if (!userObj.subkeyOK && KEY_NOT_VALID.indexOf(uidValidityStatus.charAt(0)) < 0) {
+  if (
+    !userObj.subkeyOK &&
+    !KEY_NOT_VALID.includes(uidValidityStatus.charAt(0))
+  ) {
     validity = EnigGetString("keyValid.noSubkey");
   }
 
   // process which row elements to make insensitive
-  if (((userObj.keyTrust.length > 0) &&
-      (KEY_NOT_VALID.indexOf(userObj.keyTrust.charAt(0)) >= 0)) ||
-    (!userObj.subkeyOK)) {
+  if (
+    (userObj.keyTrust.length > 0 &&
+      KEY_NOT_VALID.includes(userObj.keyTrust.charAt(0))) ||
+    !userObj.subkeyOK
+  ) {
     // disabled/revoked/expired/invalid (sub)keys inactivate whole row
     userCol.setAttribute("properties", "enigKeyInactive");
     uidValidityCol.setAttribute("properties", "enigKeyInactive");
     expCol.setAttribute("properties", "enigKeyInactive");
     keyCol.setAttribute("properties", "enigKeyInactive");
     if (!gAllowExpired && activeState >= 0) {
       activeState = 2;
     }
   } else if (!gAlwaysTrust) {
-    if (("mfu".indexOf(userObj.keyTrust.charAt(0)) < 0) ||
-      (uidValidityStatus.length > 0) &&
-      ("o-qn".indexOf(uidValidityStatus.charAt(0)) >= 0)) {
+    if (
+      !"mfu".includes(userObj.keyTrust.charAt(0)) ||
+      (uidValidityStatus.length > 0 &&
+        "o-qn".includes(uidValidityStatus.charAt(0)))
+    ) {
       // keys with not enough trust have insensitive elements, but are activateable
       userCol.setAttribute("properties", "enigKeyInactive");
       uidValidityCol.setAttribute("properties", "enigKeyInactive");
       expCol.setAttribute("properties", "enigKeyInactive");
       keyCol.setAttribute("properties", "enigKeyInactive");
     }
   }
 
@@ -652,30 +798,31 @@ function enigUserSelCreateRow(userObj, a
     if (userObj.fpr.length > 0) {
       treeItem.setAttribute("fpr", "0x" + userObj.fpr);
     }
   }
   treeItem.appendChild(userRow);
   return treeItem;
 }
 
-
 function onAccept() {
   EnigmailLog.DEBUG("enigmailKeySelection.js: Accept\n");
 
   var resultObj = window.arguments[RESULT];
   resultObj.userList = [];
   resultObj.perRecipientRules = false;
   resultObj.repeatEvaluation = false;
-  var t = "";
   gUserList = document.getElementById("enigmailUserIdSelection");
-  var treeChildren = gUserList.getElementsByAttribute("id", "enigmailUserIdSelectionChildren")[0];
+  var treeChildren = gUserList.getElementsByAttribute(
+    "id",
+    "enigmailUserIdSelectionChildren"
+  )[0];
   var item;
 
-  if (window.arguments[INPUT].options.indexOf("multisel") < 0) {
+  if (!window.arguments[INPUT].options.includes("multisel")) {
     if (gUserList.currentIndex >= 0) {
       item = gUserList.view.getItemAtIndex(gUserList.currentIndex);
       if (item.getAttribute("fpr")) {
         resultObj.userList.push(item.getAttribute("fpr"));
       } else {
         resultObj.userList.push(item.getAttribute("id"));
       }
     }
@@ -701,48 +848,55 @@ function onAccept() {
     // no longer force manual disalog even if no keys missing
     EnigSetPref("assignKeysByManuallyAlways", false);
   }
   if (resultObj.userList.length === 0 && gSendEncrypted) {
     EnigAlert(EnigGetString("atLeastOneKey"));
     return false;
   }
 
-  if ((resultObj.userList.length < getToAddrList().length) && gSendEncrypted) {
-    if (!EnigConfirm(EnigGetString("fewerKeysThanRecipients"), EnigGetString("dlg.button.continue"), EnigGetString("userSel.button.goBack")))
+  if (resultObj.userList.length < getToAddrList().length && gSendEncrypted) {
+    if (
+      !EnigConfirm(
+        EnigGetString("fewerKeysThanRecipients"),
+        EnigGetString("dlg.button.continue"),
+        EnigGetString("userSel.button.goBack")
+      )
+    ) {
       return false;
+    }
   }
 
   resultObj.cancelled = false;
 
   resultObj.encrypt = gSendEncrypted;
   resultObj.sign = gSendSigned;
   return true;
 }
 
-
 function getToAddrList() {
   var toAddrList;
   try {
-    toAddrList = EnigmailFuncs.stripEmail(window.arguments[INPUT].toAddr).split(/[ ,]+/);
+    toAddrList = EnigmailFuncs.stripEmail(window.arguments[INPUT].toAddr).split(
+      /[ ,]+/
+    );
   } catch (ex) {
     toAddrList = [];
   }
   return toAddrList;
 }
 
-
 function onClickCallback(event) {
   userSelCallback(event);
 }
 
-
 function userSelCallback(event) {
-  if (!gSendEncrypted)
+  if (!gSendEncrypted) {
     return;
+  }
 
   let Tree;
   let row;
   let col;
   if (event.type == "keypress") {
     // key event
     if (event.charCode == 32) {
       Tree = event.target;
@@ -755,76 +909,85 @@ function userSelCallback(event) {
   } else if (event.type == "click") {
     // Mouse event
     Tree = document.getElementById("enigmailUserIdSelection");
 
     let treeInfo = getCellAt(event.clientX, event.clientY);
     row = treeInfo.row;
     col = treeInfo.col;
 
-    if (!treeInfo.col) // not clicked on a valid column (e.g. scrollbar)
+    if (!treeInfo.col) {
+      // not clicked on a valid column (e.g. scrollbar)
       return;
+    }
 
-    if (event.detail > 2) return;
+    if (event.detail > 2) {
+      return;
+    }
 
-    if ((event.detail == 1) && (col.id != "selectionCol"))
-      return; // single clicks are only relevant for the selection column
+    if (event.detail == 1 && col.id != "selectionCol") {
+      return;
+    } // single clicks are only relevant for the selection column
 
-    if ((event.detail == 2) && ("selectionCol,enigUserNameCol,uidValidityCol,expCol,keyCol".indexOf(col.id) < 0))
+    if (
+      event.detail == 2 &&
+      !"selectionCol,enigUserNameCol,uidValidityCol,expCol,keyCol".includes(
+        col.id
+      )
+    ) {
       return;
+    }
 
     event.stopPropagation();
-
   }
 
-  if (row == -1)
+  if (row == -1) {
     return;
+  }
   var treeItem = Tree.view.getItemAtIndex(row);
   Tree.currentItem = treeItem;
   var aRows = treeItem.getElementsByAttribute("id", "indicator");
 
   if (event.detail == 2) {
-    if (window.arguments[INPUT].options.indexOf("multisel") < 0) {
+    if (!window.arguments[INPUT].options.includes("multisel")) {
       document.getElementById("enigmailKeySelectionDlg").acceptDialog();
       return;
     }
   }
 
   if (aRows.length) {
     var elem = aRows[0];
     if (elem.getAttribute("active") == "1") {
       EnigSetActive(elem, 0);
     } else if (elem.getAttribute("active") == "0") {
       EnigSetActive(elem, 1);
     }
   }
 }
 
-
 function switchSendSignedCallback() {
   gSendSigned = document.getElementById("enigmailUserSelSendSigned").checked;
 }
 
-
 function switchSendEncryptedCallback() {
-  gSendEncrypted = document.getElementById("enigmailUserSelSendEncrypted").checked;
+  gSendEncrypted = document.getElementById("enigmailUserSelSendEncrypted")
+    .checked;
   displayNoLonger();
   disableList();
 }
 
 function displayNoLonger() {
   var dispMsg = document.getElementById("displayNoLonger");
   if (gSendEncrypted) {
     dispMsg.setAttribute("disabled", "true");
   } else {
     dispMsg.removeAttribute("disabled");
   }
 }
 
-
 function disableList() {
   var Tree = document.getElementById("enigmailUserIdSelection");
 
   var node = Tree.firstChild.firstChild;
   while (node) {
     // set the background of all colums to gray
     if (node.localName == "treecol") {
       if (gSendEncrypted) {
@@ -832,36 +995,36 @@ function disableList() {
       } else {
         node.setAttribute("properties", "enigDontEncrypt");
       }
     }
     node = node.nextSibling;
   }
 }
 
-
 function newRecipientRule() {
   // enable rules to ensure that the new rule gets processed
   EnigSetPref("assignKeysByRules", true);
 
   var resultObj = window.arguments[RESULT];
   resultObj.userList = [];
   resultObj.repeatEvaluation = true;
   resultObj.perRecipientRules = true;
   resultObj.cancelled = false;
   resultObj.encrypt = "";
   window.close();
   return true;
 }
 
-
 function searchMissingKeys() {
   var inputObj = {
     searchList: gKeysNotFound,
-    autoKeyServer: EnigmailPrefs.getPref("autoKeyServerSelection") ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0] : null
+    autoKeyServer: EnigmailPrefs.getPref("autoKeyServerSelection")
+      ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0]
+      : null,
   };
   var resultObj = {};
 
   EnigDownloadKeys(inputObj, resultObj);
 
   if (resultObj.importedKeys > 0) {
     resultObj = window.arguments[RESULT];
     resultObj.userList = [];
@@ -871,22 +1034,24 @@ function searchMissingKeys() {
     resultObj.encrypt = "";
     window.close();
     return true;
   }
 
   return null;
 }
 
-
 function applyFilter() {
   let searchInput = document.getElementById("filterKey");
   let searchValue = searchInput.value.toLowerCase();
   let userTreeList = document.getElementById("enigmailUserIdSelection");
-  let treeChildren = userTreeList.getElementsByAttribute("id", "enigmailUserIdSelectionChildren")[0];
+  let treeChildren = userTreeList.getElementsByAttribute(
+    "id",
+    "enigmailUserIdSelectionChildren"
+  )[0];
 
   if (searchValue === "") {
     // unhide all items
     for (let item = treeChildren.firstChild; item; item = item.nextSibling) {
       item.setAttribute("hidden", false);
     }
   } else {
     // hide items that are
@@ -904,50 +1069,49 @@ function applyFilter() {
       }
       if (!showItem) {
         // check all names/emails
         let str = "";
         aRows = item.getElementsByAttribute("id", "name");
         for (let r = 0; r < aRows.length; ++r) {
           str += aRows[r].getAttribute("label");
         }
-        if (str.toLowerCase().indexOf(searchValue) >= 0) {
+        if (str.toLowerCase().includes(searchValue)) {
           showItem = true;
         }
       }
       if (!showItem) {
         // check all keys
         let str = "";
         aRows = item.getElementsByAttribute("id", "keyid");
         for (let r = 0; r < aRows.length; ++r) {
           str += aRows[r].getAttribute("label");
         }
-        if (str.toLowerCase().indexOf(searchValue) >= 0) {
+        if (str.toLowerCase().includes(searchValue)) {
           showItem = true;
         }
       }
       item.setAttribute("hidden", !showItem);
     }
   }
 }
 
-
 function stripEmailFromKey(uid) {
   try {
     return EnigmailFuncs.stripEmail(uid).toLowerCase();
   } catch (ex) {
     // remove quotes
     return EnigmailFuncs.stripEmail(uid.replace(/"/g, "")).toLowerCase();
   } finally {
     // search for last ocurrence of < >
     return uid.replace(/(.*)(<)([^<> ]+)(>[^<>]*)$/, "$3").toLowerCase(); // eslint-disable-line no-unsafe-finally
   }
 }
 
 document.addEventListener("dialogaccept", function(event) {
-  if (!onAccept())
-    event.preventDefault(); // Prevent the dialog closing.
+  if (!onAccept()) {
+    event.preventDefault();
+  } // Prevent the dialog closing.
 });
 
-
 document.addEventListener("dialogextra1", function(event) {
   newRecipientRule();
 });
--- a/mail/extensions/openpgp/content/ui/enigmailKeygen.js
+++ b/mail/extensions/openpgp/content/ui/enigmailKeygen.js
@@ -3,35 +3,40 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 // Uses: chrome://openpgp/content/ui/enigmailCommon.js
 
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
 // modules
 /* global EnigmailData: false, EnigmailLog: false, EnigmailLocale: false, EnigmailGpg: false, EnigmailKeyEditor: false */
 /* global EnigmailOS: false, EnigmailPrefs: false, EnigmailApp: false, EnigmailKeyRing: false */
 /* global EnigmailDialog: false, EnigmailFuncs: false */
 
 // from enigmailCommon.js:
 /* global EnigGetWindowOptions: false, EnigConfirm: false, EnigGetString: false, GetEnigmailSvc: false */
 /* global EnigLongAlert: false, EnigAlert: false, EnigInitCommon: false, ENIG_ACCOUNT_MANAGER_CONTRACTID: false */
 /* global EnigGetPref: false, EnigSetPref: false, EnigSavePrefs: false, EnigFilePicker: false, EnigGetFilePath: false */
 /* global EnigmailWindows: false, EnigCreateRevokeCert: false */
 
 // Initialize enigmailCommon
 EnigInitCommon("enigmailKeygen");
 
-var gAccountManager = Components.classes[ENIG_ACCOUNT_MANAGER_CONTRACTID].getService(Components.interfaces.nsIMsgAccountManager);
+var gAccountManager = Cc[ENIG_ACCOUNT_MANAGER_CONTRACTID].getService(
+  Ci.nsIMsgAccountManager
+);
+
+const EnigmailCryptoAPI = ChromeUtils.import(
+  "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
+var OpenPGPMasterpass = ChromeUtils.import(
+  "chrome://openpgp/content/modules/masterpass.jsm"
+).OpenPGPMasterpass;
 
 var gUserIdentityList;
 var gUserIdentityListPopup;
 var gUseForSigning;
 
 var gKeygenRequest;
 var gAllData = "";
 var gGeneratedKey = null;
@@ -75,73 +80,92 @@ function updateKeySizeSel(selectedObj) {
   } else {
     document.getElementById("keySize").removeAttribute("disabled");
   }
 }
 
 function enigmailOnClose() {
   var closeWin = true;
   if (gKeygenRequest) {
-    closeWin = EnigConfirm(EnigGetString("keyAbort"), EnigGetString("keyMan.button.generateKeyAbort"), EnigGetString("keyMan.button.generateKeyContinue"));
+    closeWin = EnigConfirm(
+      EnigGetString("keyAbort"),
+      EnigGetString("keyMan.button.generateKeyAbort"),
+      EnigGetString("keyMan.button.generateKeyContinue")
+    );
   }
-  if (closeWin) abortKeyGeneration();
+  if (closeWin) {
+    abortKeyGeneration();
+  }
   return closeWin;
 }
 
 function enigmailKeygenUnload() {
   EnigmailLog.DEBUG("enigmailKeygen.js: Unload\n");
 
   enigmailKeygenCloseRequest();
 }
 
 function enigmailKeygenTerminate(exitCode) {
   EnigmailLog.DEBUG("enigmailKeygen.js: Terminate:\n");
 
   var curId = gUsedId;
 
   gKeygenRequest = null;
 
-  if ((!gGeneratedKey) || gGeneratedKey == KEYGEN_CANCELLED) {
-    if (!gGeneratedKey)
+  if (!gGeneratedKey || gGeneratedKey == KEYGEN_CANCELLED) {
+    if (!gGeneratedKey) {
       EnigAlert(EnigGetString("keyGenFailed"));
+    }
     return;
   }
 
   var progMeter = document.getElementById("keygenProgress");
   progMeter.setAttribute("value", 100);
 
   if (gGeneratedKey) {
     if (gUseForSigning.checked) {
       curId.setBoolAttribute("enablePgp", true);
       curId.setIntAttribute("pgpKeyMode", 1);
       curId.setCharAttribute("pgpkeyId", "0x" + gGeneratedKey);
 
       EnigSavePrefs();
 
       EnigmailWindows.keyManReloadKeys();
 
-      if (EnigConfirm(EnigGetString("keygenComplete", curId.email) + "\n\n" + EnigGetString("revokeCertRecommended"), EnigGetString("keyMan.button.generateCert"))) {
+      if (
+        EnigConfirm(
+          EnigGetString("keygenComplete", curId.email) +
+            "\n\n" +
+            EnigGetString("revokeCertRecommended"),
+          EnigGetString("keyMan.button.generateCert")
+        )
+      ) {
         EnigCreateRevokeCert(gGeneratedKey, curId.email, closeAndReset);
       } else {
         closeAndReset();
       }
+    } else if (
+      EnigConfirm(
+        EnigGetString("genCompleteNoSign") +
+          "\n\n" +
+          EnigGetString("revokeCertRecommended"),
+        EnigGetString("keyMan.button.generateCert")
+      )
+    ) {
+      EnigCreateRevokeCert(gGeneratedKey, curId.email, closeAndReset);
+      genAndSaveRevCert(gGeneratedKey, curId.email).then(
+        function() {
+          closeAndReset();
+        },
+        function() {
+          // do nothing
+        }
+      );
     } else {
-      if (EnigConfirm(EnigGetString("genCompleteNoSign") + "\n\n" + EnigGetString("revokeCertRecommended"), EnigGetString("keyMan.button.generateCert"))) {
-        EnigCreateRevokeCert(gGeneratedKey, curId.email, closeAndReset);
-        genAndSaveRevCert(gGeneratedKey, curId.email).then(
-          function _resolve() {
-            closeAndReset();
-          },
-          function _reject() {
-            // do nothing
-          }
-        );
-      } else {
-        closeAndReset();
-      }
+      closeAndReset();
     }
   } else {
     EnigAlert(EnigGetString("keyGenFailed"));
     window.close();
   }
 }
 
 /**
@@ -154,23 +178,27 @@ function genAndSaveRevCert(keyId, uid) {
   EnigmailLog.DEBUG("enigmailKeygen.js: genAndSaveRevCert\n");
   throw new Error("Not implemented");
 }
 
 /**
  *  create a copy of the revokation cert at a user defined location
  */
 function saveRevCert(inputKeyFile, keyId, uid, resolve, reject) {
-
   let defaultFileName = uid.replace(/[\\/<>]/g, "");
   defaultFileName += " (0x" + keyId + ") rev.asc";
 
-  let outFile = EnigFilePicker(EnigGetString("saveRevokeCertAs"),
-    "", true, "*.asc",
-    defaultFileName, [EnigGetString("asciiArmorFile"), "*.asc"]);
+  let outFile = EnigFilePicker(
+    EnigGetString("saveRevokeCertAs"),
+    "",
+    true,
+    "*.asc",
+    defaultFileName,
+    [EnigGetString("asciiArmorFile"), "*.asc"]
+  );
 
   if (outFile) {
     try {
       inputKeyFile.copyToFollowingLinks(outFile.parent, outFile.leafName);
       EnigmailDialog.info(window, EnigGetString("revokeCertOK"));
     } catch (ex) {
       EnigAlert(EnigGetString("revokeCertFailed"));
       reject(2);
@@ -194,17 +222,17 @@ function enigmailKeygenCloseRequest() {
     p.kill(false);
   }
 }
 
 function enigmailKeygenStart() {
   EnigmailLog.DEBUG("enigmailKeygen.js: Start\n");
 
   if (gKeygenRequest) {
-    let req = gKeygenRequest.QueryInterface(Components.interfaces.nsIRequest);
+    let req = gKeygenRequest.QueryInterface(Ci.nsIRequest);
     if (req.isPending()) {
       EnigmailDialog.info(window, EnigGetString("genGoing"));
       return;
     }
   }
 
   gGeneratedKey = null;
   gAllData = "";
@@ -252,22 +280,29 @@ function enigmailKeygenStart() {
   var confirmMsg = EnigGetString("keyConfirm", idString);
 
   if (!EnigConfirm(confirmMsg, EnigGetString("keyMan.button.generateKey"))) {
     return;
   }
 
   try {
     const cApi = EnigmailCryptoAPI();
-    let newId = cApi.sync(cApi.genKey(idString, keyType, keySize, expiryTime,
-                                      OpenPGPMasterpass.retrieveOpenPGPPassword()));
+    let newId = cApi.sync(
+      cApi.genKey(
+        idString,
+        keyType,
+        keySize,
+        expiryTime,
+        OpenPGPMasterpass.retrieveOpenPGPPassword()
+      )
+    );
     console.log("created new key with id: " + newId);
-  } catch(ex) {
+  } catch (ex) {
     console.log(ex);
-  } 
+  }
 
   EnigmailWindows.keyManReloadKeys();
   closeAndReset();
 
   /*
   var proc = null;
 
   var listener = {
@@ -321,107 +356,125 @@ function abortKeyGeneration() {
   enigmailKeygenCloseRequest();
 }
 
 function enigmailKeygenCancel() {
   EnigmailLog.DEBUG("enigmailKeygen.js: Cancel\n");
   var closeWin = false;
 
   if (gKeygenRequest) {
-    closeWin = EnigConfirm(EnigGetString("keyAbort"), EnigGetString("keyMan.button.generateKeyAbort"), EnigGetString("keyMan.button.generateKeyContinue"));
-    if (closeWin) abortKeyGeneration();
+    closeWin = EnigConfirm(
+      EnigGetString("keyAbort"),
+      EnigGetString("keyMan.button.generateKeyAbort"),
+      EnigGetString("keyMan.button.generateKeyContinue")
+    );
+    if (closeWin) {
+      abortKeyGeneration();
+    }
   } else {
     closeWin = true;
   }
 
-  if (closeWin) window.close();
+  if (closeWin) {
+    window.close();
+  }
 }
 
 function onNoExpiry() {
   var noExpiry = document.getElementById("noExpiry");
   var expireInput = document.getElementById("expireInput");
   var timeScale = document.getElementById("timeScale");
 
   expireInput.disabled = noExpiry.checked;
   timeScale.disabled = noExpiry.checked;
 }
 
-
 function queryISupArray(supportsArray, iid) {
   var result = [];
   var i;
   // Gecko > 20
   for (i = 0; i < supportsArray.length; i++) {
     result.push(supportsArray.queryElementAt(i, iid));
   }
 
   return result;
 }
 
 function getCurrentIdentity() {
   var item = gUserIdentityList.selectedItem;
-  var identityKey = item.getAttribute('id');
+  var identityKey = item.getAttribute("id");
 
   var identity = gAccountManager.getIdentity(identityKey);
 
   return identity;
 }
 
 function fillIdentityListPopup() {
   EnigmailLog.DEBUG("enigmailKeygen.js: fillIdentityListPopup\n");
 
   try {
     var idSupports = gAccountManager.allIdentities;
-    var identities = queryISupArray(idSupports,
-      Components.interfaces.nsIMsgIdentity);
+    var identities = queryISupArray(idSupports, Ci.nsIMsgIdentity);
 
-    EnigmailLog.DEBUG("enigmailKeygen.js: fillIdentityListPopup: " + identities + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailKeygen.js: fillIdentityListPopup: " + identities + "\n"
+    );
 
     // Default identity
     let defIdentity = EnigmailFuncs.getDefaultIdentity();
 
-    EnigmailLog.DEBUG("enigmailKeygen.js: fillIdentityListPopup: default=" + defIdentity.key + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailKeygen.js: fillIdentityListPopup: default=" +
+        defIdentity.key +
+        "\n"
+    );
 
     var selected = false;
     for (var i = 0; i < identities.length; i++) {
       var identity = identities[i];
 
       EnigmailLog.DEBUG("id.valid=" + identity.valid + "\n");
-      if (!identity.valid || !identity.email)
+      if (!identity.valid || !identity.email) {
         continue;
+      }
 
       var serverSupports, inServer;
       // Gecko >= 20
       serverSupports = gAccountManager.getServersForIdentity(identity);
       if (serverSupports.length > 0) {
-        inServer = serverSupports.queryElementAt(0, Components.interfaces.nsIMsgIncomingServer);
+        inServer = serverSupports.queryElementAt(0, Ci.nsIMsgIncomingServer);
       }
 
       if (inServer) {
         var accountName = " - " + inServer.prettyName;
 
-        EnigmailLog.DEBUG("enigmailKeygen.js: accountName=" + accountName + "\n");
+        EnigmailLog.DEBUG(
+          "enigmailKeygen.js: accountName=" + accountName + "\n"
+        );
         EnigmailLog.DEBUG("enigmailKeygen.js: email=" + identity.email + "\n");
 
-        var item = document.createXULElement('menuitem');
+        var item = document.createXULElement("menuitem");
         //      item.setAttribute('label', identity.identityName);
-        item.setAttribute('label', identity.identityName + accountName);
-        item.setAttribute('class', 'identity-popup-item');
-        item.setAttribute('accountname', accountName);
-        item.setAttribute('id', identity.key);
-        item.setAttribute('email', identity.email);
+        item.setAttribute("label", identity.identityName + accountName);
+        item.setAttribute("class", "identity-popup-item");
+        item.setAttribute("accountname", accountName);
+        item.setAttribute("id", identity.key);
+        item.setAttribute("email", identity.email);
 
         gUserIdentityListPopup.appendChild(item);
 
-        if (!selected)
+        if (!selected) {
           gUserIdentityList.selectedItem = item;
+        }
 
         if (identity.key == defIdentity.key) {
           gUserIdentityList.selectedItem = item;
           selected = true;
         }
       }
     }
-  }
-  catch(ex) {
-    EnigmailLog.writeException("enigmailKeygen.js: fillIdentityListPopup: exception\n", ex);
+  } catch (ex) {
+    EnigmailLog.writeException(
+      "enigmailKeygen.js: fillIdentityListPopup: exception\n",
+      ex
+    );
   }
 }
--- a/mail/extensions/openpgp/content/ui/enigmailMessengerOverlay.js
+++ b/mail/extensions/openpgp/content/ui/enigmailMessengerOverlay.js
@@ -1,58 +1,128 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
+// TODO: check if this is safe
+/* eslint-disable no-unsanitized/property */
+
 /* Globals from Thunderbird: */
 /* global ReloadMessage: false, gDBView: false, gSignatureStatus: false, gEncryptionStatus: false, showMessageReadSecurityInfo: false */
 /* global gFolderDisplay: false, messenger: false, currentAttachments: false, msgWindow: false, PanelUI: false */
 /* global currentHeaderData: false, gViewAllHeaders: false, gExpandedHeaderList: false, goDoCommand: false, HandleSelectedAttachments: false */
 /* global statusFeedback: false, displayAttachmentsForExpandedView: false, gMessageListeners: false, gExpandedHeaderView */
 
-var EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-var EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailMsgRead = ChromeUtils.import("chrome://openpgp/content/modules/msgRead.jsm").EnigmailMsgRead;
-var EnigmailVerify = ChromeUtils.import("chrome://openpgp/content/modules/mimeVerify.jsm").EnigmailVerify;
-var EnigmailVerifyAttachment = ChromeUtils.import("chrome://openpgp/content/modules/verify.jsm").EnigmailVerifyAttachment;
-var EnigmailFixExchangeMsg = ChromeUtils.import("chrome://openpgp/content/modules/fixExchangeMsg.jsm").EnigmailFixExchangeMsg;
-var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-var EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-var EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-var EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-var EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-var EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-var EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-var EnigmailPersistentCrypto = ChromeUtils.import("chrome://openpgp/content/modules/persistentCrypto.jsm").EnigmailPersistentCrypto;
-var EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-var EnigmailEvents = ChromeUtils.import("chrome://openpgp/content/modules/events.jsm").EnigmailEvents;
-var EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-var EnigmailDecryption = ChromeUtils.import("chrome://openpgp/content/modules/decryption.jsm").EnigmailDecryption;
-var EnigmailAttachment = ChromeUtils.import("chrome://openpgp/content/modules/attachment.jsm").EnigmailAttachment;
-var EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-var EnigmailKeyUsability = ChromeUtils.import("chrome://openpgp/content/modules/keyUsability.jsm").EnigmailKeyUsability;
-var EnigmailURIs = ChromeUtils.import("chrome://openpgp/content/modules/uris.jsm").EnigmailURIs;
-var EnigmailProtocolHandler = ChromeUtils.import("chrome://openpgp/content/modules/protocolHandler.jsm").EnigmailProtocolHandler;
-var EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
-var EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-var EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-var EnigmailWks = ChromeUtils.import("chrome://openpgp/content/modules/webKey.jsm").EnigmailWks;
-var EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-var EnigmailConfigure = ChromeUtils.import("chrome://openpgp/content/modules/configure.jsm").EnigmailConfigure;
-var Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
+var EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+var EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailMsgRead = ChromeUtils.import(
+  "chrome://openpgp/content/modules/msgRead.jsm"
+).EnigmailMsgRead;
+var EnigmailVerify = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mimeVerify.jsm"
+).EnigmailVerify;
+var EnigmailVerifyAttachment = ChromeUtils.import(
+  "chrome://openpgp/content/modules/verify.jsm"
+).EnigmailVerifyAttachment;
+var EnigmailFixExchangeMsg = ChromeUtils.import(
+  "chrome://openpgp/content/modules/fixExchangeMsg.jsm"
+).EnigmailFixExchangeMsg;
+var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm")
+  .EnigmailLog;
+var EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm")
+  .EnigmailKey;
+var EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+var EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm")
+  .EnigmailApp;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+var EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+var EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+var EnigmailTime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/time.jsm"
+).EnigmailTime;
+var EnigmailPersistentCrypto = ChromeUtils.import(
+  "chrome://openpgp/content/modules/persistentCrypto.jsm"
+).EnigmailPersistentCrypto;
+var EnigmailStreams = ChromeUtils.import(
+  "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+var EnigmailEvents = ChromeUtils.import(
+  "chrome://openpgp/content/modules/events.jsm"
+).EnigmailEvents;
+var EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+var EnigmailDecryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/decryption.jsm"
+).EnigmailDecryption;
+var EnigmailAttachment = ChromeUtils.import(
+  "chrome://openpgp/content/modules/attachment.jsm"
+).EnigmailAttachment;
+var EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+var EnigmailKeyUsability = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyUsability.jsm"
+).EnigmailKeyUsability;
+var EnigmailURIs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/uris.jsm"
+).EnigmailURIs;
+var EnigmailProtocolHandler = ChromeUtils.import(
+  "chrome://openpgp/content/modules/protocolHandler.jsm"
+).EnigmailProtocolHandler;
+var EnigmailAutocrypt = ChromeUtils.import(
+  "chrome://openpgp/content/modules/autocrypt.jsm"
+).EnigmailAutocrypt;
+var EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+var EnigmailArmor = ChromeUtils.import(
+  "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+var EnigmailWks = ChromeUtils.import(
+  "chrome://openpgp/content/modules/webKey.jsm"
+).EnigmailWks;
+var EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+var EnigmailConfigure = ChromeUtils.import(
+  "chrome://openpgp/content/modules/configure.jsm"
+).EnigmailConfigure;
+var Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 var Enigmail;
 if (!Enigmail) {
   Enigmail = {};
 }
 
 Enigmail.getEnigmailSvc = function() {
   return EnigmailCore.getService(window);
@@ -64,216 +134,246 @@ Enigmail.msg = {
   securityInfo: null,
   lastSaveDir: "",
   messagePane: null,
   noShowReload: false,
   decryptButton: null,
   savedHeaders: null,
   removeListener: false,
   enableExperiments: false,
-  headersList: ["content-transfer-encoding",
-    "x-enigmail-version", "x-pgp-encoding-format",
-    "autocrypt-setup-message"
+  headersList: [
+    "content-transfer-encoding",
+    "x-enigmail-version",
+    "x-pgp-encoding-format",
+    "autocrypt-setup-message",
   ],
   buggyExchangeEmailContent: null, // for HACK for MS-EXCHANGE-Server Problem
   buggyMailType: null,
   changedAttributes: [],
   lastSMimeReloadURI: "",
 
-  messengerStartup: function() {
-
+  messengerStartup() {
     let self = this;
 
     // private function to overwrite attributes
     function overrideAttribute(elementIdList, attrName, prefix, suffix) {
       for (var index = 0; index < elementIdList.length; index++) {
         var elementId = elementIdList[index];
         var element = document.getElementById(elementId);
         if (element) {
           try {
             var oldValue = element.getAttribute(attrName);
-            EnigmailLog.DEBUG("enigmailMessengerOverlay.js: overrideAttribute " + attrName + ": oldValue=" + oldValue + "\n");
+            EnigmailLog.DEBUG(
+              "enigmailMessengerOverlay.js: overrideAttribute " +
+                attrName +
+                ": oldValue=" +
+                oldValue +
+                "\n"
+            );
             var newValue = prefix + elementId + suffix;
 
             element.setAttribute(attrName, newValue);
             self.changedAttributes.push({
               id: elementId,
               attrib: attrName,
-              value: oldValue
+              value: oldValue,
             });
-          }
-          catch (ex) {}
-        }
-        else {
-          EnigmailLog.DEBUG("enigmailMessengerOverlay.js: *** UNABLE to override id=" + elementId + "\n");
+          } catch (ex) {}
+        } else {
+          EnigmailLog.DEBUG(
+            "enigmailMessengerOverlay.js: *** UNABLE to override id=" +
+              elementId +
+              "\n"
+          );
         }
       }
     }
 
     Enigmail.msg.messagePane = document.getElementById("messagepane");
 
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: Startup\n");
 
     // Override SMIME ui
-    overrideAttribute(["cmd_viewSecurityStatus"], "Enigmail.msg.viewSecurityInfo(null, true);", "", "");
+    overrideAttribute(
+      ["cmd_viewSecurityStatus"],
+      "Enigmail.msg.viewSecurityInfo(null, true);",
+      "",
+      ""
+    );
 
     // Override print command
-    var printElementIds = ["cmd_print", "cmd_printpreview", "key_print", "button-print",
-      "mailContext-print", "mailContext-printpreview"
+    var printElementIds = [
+      "cmd_print",
+      "cmd_printpreview",
+      "key_print",
+      "button-print",
+      "mailContext-print",
+      "mailContext-printpreview",
     ];
 
-    overrideAttribute(printElementIds, "oncommand",
-      "Enigmail.msg.msgPrint('", "');");
+    overrideAttribute(
+      printElementIds,
+      "oncommand",
+      "Enigmail.msg.msgPrint('",
+      "');"
+    );
 
     //Enigmail.msg.overrideLayoutChange();
     Enigmail.msg.prepareAppMenu();
     Enigmail.msg.setMainMenuLabel();
 
     let statusCol = document.getElementById("enigmailStatusCol");
     if (statusCol) {
-      statusCol.setAttribute("label", EnigmailLocale.getString("enigmail.msgViewColumn.label"));
+      statusCol.setAttribute(
+        "label",
+        EnigmailLocale.getString("enigmail.msgViewColumn.label")
+      );
     }
 
     Enigmail.msg.savedHeaders = null;
 
-    Enigmail.msg.decryptButton = document.getElementById("button-enigmail-decrypt");
-
-    EnigmailTimer.setTimeout(function _f() {
+    Enigmail.msg.decryptButton = document.getElementById(
+      "button-enigmail-decrypt"
+    );
+
+    EnigmailTimer.setTimeout(function() {
       // if nothing happened, then load all keys after 1 hour
       // to trigger the key check
       EnigmailKeyRing.getAllKeys();
-
     }, 3600 * 1000); // 1 hour
 
     // Need to add event listener to Enigmail.msg.messagePane to make it work
     // Adding to msgFrame doesn't seem to work
-    Enigmail.msg.messagePane.addEventListener("unload", Enigmail.msg.messageFrameUnload.bind(Enigmail.msg), true);
+    Enigmail.msg.messagePane.addEventListener(
+      "unload",
+      Enigmail.msg.messageFrameUnload.bind(Enigmail.msg),
+      true
+    );
 
     this.treeController = {
-      supportsCommand: function(command) {
+      supportsCommand(command) {
         // EnigmailLog.DEBUG("enigmailMessengerOverlay.js: treeCtrl: supportsCommand: "+command+"\n");
         switch (command) {
           case "button_enigmail_decrypt":
             return true;
         }
         return false;
       },
-      isCommandEnabled: function(command) {
+      isCommandEnabled(command) {
         // EnigmailLog.DEBUG("enigmailMessengerOverlay.js: treeCtrl: isCommandEnabled: "+command+"\n");
         try {
           if (gFolderDisplay.messageDisplay.visible) {
             if (gFolderDisplay.selectedCount != 1) {
               Enigmail.hdrView.statusBarHide();
             }
-            return (gFolderDisplay.selectedCount == 1);
+            return gFolderDisplay.selectedCount == 1;
           }
           Enigmail.hdrView.statusBarHide();
-        }
-        catch (ex) {}
+        } catch (ex) {}
         return false;
       },
-      doCommand: function(command) {
+      doCommand(command) {
         //EnigmailLog.DEBUG("enigmailMessengerOverlay.js: treeCtrl: doCommand: "+command+"\n");
         // nothing
       },
-      onEvent: function(event) {
+      onEvent(event) {
         // EnigmailLog.DEBUG("enigmailMessengerOverlay.js: treeCtrl: onEvent: "+command+"\n");
         // nothing
-      }
+      },
     };
 
     top.controllers.appendController(this.treeController);
 
     if (EnigmailPrefs.getPref("configuredVersion") === "") {
       EnigmailConfigure.configureEnigmail(window, false);
     }
 
     EnigmailMsgRead.ensureExtraAddonHeaders();
     gMessageListeners.push(Enigmail.msg.messageListener);
     Enigmail.msg.messageListener.onEndHeaders();
   },
 
   messageListener: {
-    onStartHeaders: function() {
+    onStartHeaders() {
       Enigmail.msg.mimeParts = null;
       if ("autocrypt" in gExpandedHeaderView) {
         delete gExpandedHeaderView.autocrypt;
       }
       if ("openpgp" in gExpandedHeaderView) {
         delete gExpandedHeaderView.openpgp;
       }
     },
-    onEndHeaders: function() {},
-    onEndAttachments: function() {}
+    onEndHeaders() {},
+    onEndAttachments() {},
   },
 
-  viewSecurityInfo: function(event, displaySmimeMsg) {
+  viewSecurityInfo(event, displaySmimeMsg) {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: viewSecurityInfo\n");
 
     if (event && event.button !== 0) {
       return;
     }
 
     if (gSignatureStatus >= 0 || gEncryptionStatus >= 0) {
       showMessageReadSecurityInfo();
-    }
-    else {
-      if (Enigmail.msg.securityInfo) {
-        this.viewOpenpgpInfo();
-      }
-      else {
-        showMessageReadSecurityInfo();
-      }
+    } else if (Enigmail.msg.securityInfo) {
+      this.viewOpenpgpInfo();
+    } else {
+      showMessageReadSecurityInfo();
     }
   },
 
-  viewOpenpgpInfo: function() {
+  viewOpenpgpInfo() {
     if (Enigmail.msg.securityInfo) {
       // Thunderbird
-      EnigmailDialog.info(window, EnigmailLocale.getString("securityInfo") + Enigmail.msg.securityInfo.statusInfo);
+      EnigmailDialog.info(
+        window,
+        EnigmailLocale.getString("securityInfo") +
+          Enigmail.msg.securityInfo.statusInfo
+      );
     }
   },
 
-  clearLastMessage: function() {
-    const {
-      EnigmailSingletons
-    } = ChromeUtils.import("chrome://openpgp/content/modules/singletons.jsm");
+  clearLastMessage() {
+    const { EnigmailSingletons } = ChromeUtils.import(
+      "chrome://openpgp/content/modules/singletons.jsm"
+    );
     EnigmailSingletons.clearLastDecryptedMessage();
   },
 
-  messageReload: function(noShowReload) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageReload: " + noShowReload + "\n");
+  messageReload(noShowReload) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: messageReload: " + noShowReload + "\n"
+    );
 
     Enigmail.msg.noShowReload = noShowReload;
     this.clearLastMessage();
     ReloadMessage();
   },
 
-  messengerClose: function() {
+  messengerClose() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messengerClose()\n");
   },
 
-  reloadCompleteMsg: function() {
+  reloadCompleteMsg() {
     this.clearLastMessage();
     gDBView.reloadMessageWithAllParts();
   },
 
-
-  setAttachmentReveal: function(attachmentList) {
+  setAttachmentReveal(attachmentList) {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: setAttachmentReveal\n");
 
     var revealBox = document.getElementById("enigmailRevealAttachments");
     if (revealBox) {
       // there are situations when evealBox is not yet present
       revealBox.setAttribute("hidden", !attachmentList ? "true" : "false");
     }
   },
 
-
-  messageCleanup: function() {
+  messageCleanup() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageCleanup\n");
 
     var enigmailBox = document.getElementById("enigmailBox");
 
     if (enigmailBox && !enigmailBox.collapsed) {
       enigmailBox.setAttribute("collapsed", "true");
 
       var statusText = document.getElementById("expandedEnigmailStatusText");
@@ -288,101 +388,104 @@ Enigmail.msg = {
     }
 
     this.setAttachmentReveal(null);
 
     if (Enigmail.msg.createdURIs.length) {
       // Cleanup messages belonging to this window (just in case)
       var enigmailSvc = Enigmail.getEnigmailSvc();
       if (enigmailSvc) {
-        EnigmailLog.DEBUG("enigmailMessengerOverlay.js: Cleanup: Deleting messages\n");
+        EnigmailLog.DEBUG(
+          "enigmailMessengerOverlay.js: Cleanup: Deleting messages\n"
+        );
         for (var index = 0; index < Enigmail.msg.createdURIs.length; index++) {
           EnigmailURIs.deleteMessageURI(Enigmail.msg.createdURIs[index]);
         }
         Enigmail.msg.createdURIs = [];
       }
     }
 
     Enigmail.msg.decryptedMessage = null;
     Enigmail.msg.securityInfo = null;
   },
 
-  messageFrameUnload: function() {
+  messageFrameUnload() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageFrameUnload\n");
 
     if (Enigmail.msg.noShowReload) {
       Enigmail.msg.noShowReload = false;
-
-    }
-    else {
+    } else {
       Enigmail.msg.savedHeaders = null;
 
       Enigmail.msg.messageCleanup();
     }
   },
 
-  getCurrentMsgUriSpec: function() {
+  getCurrentMsgUriSpec() {
     try {
       // Thunderbird
       if (gFolderDisplay.selectedMessages.length != 1) {
         return "";
       }
 
       var uriSpec = gFolderDisplay.selectedMessageUris[0];
       //EnigmailLog.DEBUG("enigmailMessengerOverlay.js: getCurrentMsgUriSpec: uriSpec="+uriSpec+"\n");
 
       return uriSpec;
-    }
-    catch (ex) {
+    } catch (ex) {
       return "";
     }
   },
 
-  getCurrentMsgUrl: function() {
+  getCurrentMsgUrl() {
     var uriSpec = this.getCurrentMsgUriSpec();
     return EnigmailMsgRead.getUrlFromUriSpec(uriSpec);
   },
 
-  updateOptionsDisplay: function() {
+  updateOptionsDisplay() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: updateOptionsDisplay: \n");
     var optList = ["autoDecrypt"];
 
     for (let j = 0; j < optList.length; j++) {
       let menuElement = document.getElementById("enigmail_" + optList[j]);
-      menuElement.setAttribute("checked", EnigmailPrefs.getPref(optList[j]) ? "true" : "false");
+      menuElement.setAttribute(
+        "checked",
+        EnigmailPrefs.getPref(optList[j]) ? "true" : "false"
+      );
 
       menuElement = document.getElementById("enigmail_" + optList[j] + "2");
       if (menuElement) {
-        menuElement.setAttribute("checked", EnigmailPrefs.getPref(optList[j]) ? "true" : "false");
+        menuElement.setAttribute(
+          "checked",
+          EnigmailPrefs.getPref(optList[j]) ? "true" : "false"
+        );
       }
     }
 
     optList = ["decryptverify"];
     for (let j = 0; j < optList.length; j++) {
       let menuElement = document.getElementById("enigmail_" + optList[j]);
       if (Enigmail.msg.decryptButton && Enigmail.msg.decryptButton.disabled) {
         menuElement.setAttribute("disabled", "true");
-      }
-      else {
+      } else {
         menuElement.removeAttribute("disabled");
       }
 
       menuElement = document.getElementById("enigmail_" + optList[j] + "2");
       if (menuElement) {
         if (Enigmail.msg.decryptButton && Enigmail.msg.decryptButton.disabled) {
           menuElement.setAttribute("disabled", "true");
-        }
-        else {
+        } else {
           menuElement.removeAttribute("disabled");
         }
       }
     }
   },
 
-  setMainMenuLabel: function() {
+  setMainMenuLabel() {
     let o = ["menu_Enigmail", "appmenu-Enigmail"];
 
     let m0 = document.getElementById(o[0]);
     let m1 = document.getElementById(o[1]);
 
     m1.setAttribute("enigmaillabel", m0.getAttribute("enigmaillabel"));
 
     for (let menuId of o) {
@@ -390,250 +493,288 @@ Enigmail.msg = {
 
       if (menu) {
         let lbl = menu.getAttribute("enigmaillabel");
         menu.setAttribute("label", lbl);
       }
     }
   },
 
-  prepareAppMenu: function() {
+  prepareAppMenu() {
     let menu = document.querySelector("#appMenu-mainView > vbox");
-    if (!menu) return;
+    if (!menu) {
+      return;
+    }
 
     // don't try to add Enigmail menu more than once
-    if (document.getElementById("appmenu-Enigmail")) return;
+    if (document.getElementById("appmenu-Enigmail")) {
+      return;
+    }
 
     let tsk = document.getElementById("appmenu_tasksMenu");
     let e = document.createXULElement("toolbarbutton");
     e.setAttribute("label", "xxEnigmail");
     e.id = "appmenu-Enigmail";
-    e.setAttribute("class", "subviewbutton subviewbutton-nav subviewbutton-iconic");
+    e.setAttribute(
+      "class",
+      "subviewbutton subviewbutton-nav subviewbutton-iconic"
+    );
     e.setAttribute("closemenu", "none");
-    e.setAttribute("oncommand", "Enigmail.msg.displayAppmenu('appMenu-enigmailView', this)");
+    e.setAttribute(
+      "oncommand",
+      "Enigmail.msg.displayAppmenu('appMenu-enigmailView', this)"
+    );
     e.setAttribute("overlay_source", "enigmail");
     menu.insertBefore(e, tsk);
   },
 
-  displayAppmenu: function(targetId, targetObj) {
+  displayAppmenu(targetId, targetObj) {
     let menuElem = document.getElementById("appmenu_enigmailMenuPlaceholder");
     this.displayMainMenu(menuElem);
     PanelUI.showSubView(targetId, targetObj);
   },
 
-  displayMainMenu: function(menuPopup) {
-
+  displayMainMenu(menuPopup) {
     let obj = menuPopup.firstChild;
 
     while (obj) {
-      if (obj.getAttribute("enigmailtype") == "enigmail" || obj.getAttribute("advanced") == "true") {
+      if (
+        obj.getAttribute("enigmailtype") == "enigmail" ||
+        obj.getAttribute("advanced") == "true"
+      ) {
         obj.removeAttribute("hidden");
       }
 
       obj = obj.nextSibling;
     }
 
-    EnigmailFuncs.collapseAdvanced(menuPopup, 'hidden', Enigmail.msg.updateOptionsDisplay());
+    EnigmailFuncs.collapseAdvanced(
+      menuPopup,
+      "hidden",
+      Enigmail.msg.updateOptionsDisplay()
+    );
   },
 
-  toggleAttribute: function(attrName) {
-    EnigmailLog.DEBUG("enigmailMsgessengerOverlay.js: toggleAttribute('" + attrName + "')\n");
-
-    var menuElement = document.getElementById("enigmail_" + attrName);
+  toggleAttribute(attrName) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgessengerOverlay.js: toggleAttribute('" + attrName + "')\n"
+    );
 
     var oldValue = EnigmailPrefs.getPref(attrName);
     EnigmailPrefs.setPref(attrName, !oldValue);
 
     this.updateOptionsDisplay();
 
     if (attrName == "autoDecrypt") {
       this.messageReload(false);
     }
   },
 
   /**
    * Determine if Autocrypt is enabled for the currently selected message
    */
-  isAutocryptEnabled: function() {
+  isAutocryptEnabled() {
     try {
-      let email = EnigmailFuncs.stripEmail(gFolderDisplay.selectedMessage.recipients);
+      let email = EnigmailFuncs.stripEmail(
+        gFolderDisplay.selectedMessage.recipients
+      );
       let maybeIdent = EnigmailStdlib.getIdentityForEmail(email);
 
       if (maybeIdent && maybeIdent.identity) {
         if (!maybeIdent.identity.getBoolAttribute("enablePgp")) {
           return false;
         }
 
         let acct = EnigmailFuncs.getAccountForIdentity(maybeIdent.identity);
         return acct.incomingServer.getBoolValue("enableAutocrypt");
       }
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     return false;
   },
 
-  messageImport: function() {
+  messageImport() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageImport:\n");
 
-    return this.messageParse(true, true, "", this.getCurrentMsgUriSpec(), false);
+    return this.messageParse(
+      true,
+      true,
+      "",
+      this.getCurrentMsgUriSpec(),
+      false
+    );
   },
 
   /***
    * check that handler for multipart/signed is set to Enigmail.
    * if handler is different, change it and reload message
    *
    * @return: - true if handler is OK
    *          - false if handler was changed and message is reloaded
    */
-  checkPgpmimeHandler: function() {
+  checkPgpmimeHandler() {
     let uriSpec = this.getCurrentMsgUriSpec();
     if (uriSpec !== this.lastSMimeReloadURI) {
-      if (EnigmailVerify.currentCtHandler !== EnigmailConstants.MIME_HANDLER_PGPMIME) {
+      if (
+        EnigmailVerify.currentCtHandler !==
+        EnigmailConstants.MIME_HANDLER_PGPMIME
+      ) {
         this.lastSMimeReloadURI = uriSpec;
         EnigmailVerify.registerContentTypeHandler();
         this.messageReload();
         return false;
       }
     }
 
     return true;
   },
 
   // callback function for automatic decryption
-  messageAutoDecrypt: function() {
+  messageAutoDecrypt() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageAutoDecrypt:\n");
     Enigmail.msg.messageDecrypt(null, true);
   },
 
   // analyse message header and decrypt/verify message
-  messageDecrypt: function(event, isAuto) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageDecrypt: " + event + "\n");
-
-    event = event ? true : false;
-    var cbObj = {
-      event: event,
-      isAuto: isAuto
-    };
+  messageDecrypt(event, isAuto) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: messageDecrypt: " + event + "\n"
+    );
+
+    event = !!event;
 
     this.mimeParts = null;
 
     if (!isAuto) {
       EnigmailVerify.setManualUri(this.getCurrentMsgUriSpec());
     }
 
     let contentType = "text/plain";
-    if ('content-type' in currentHeaderData) {
-      contentType = currentHeaderData['content-type'].headerValue;
+    if ("content-type" in currentHeaderData) {
+      contentType = currentHeaderData["content-type"].headerValue;
     }
 
-
     // don't parse message if we know it's a PGP/MIME message
-    if (contentType.search(/^multipart\/encrypted(;|$)/i) === 0 && contentType.search(/application\/pgp-encrypted/i) > 0) {
+    if (
+      contentType.search(/^multipart\/encrypted(;|$)/i) === 0 &&
+      contentType.search(/application\/pgp-encrypted/i) > 0
+    ) {
       this.movePEPsubject();
       this.messageDecryptCb(event, isAuto, null);
       return;
-    }
-    else if (contentType.search(/^multipart\/signed(;|$)/i) === 0 && contentType.search(/application\/pgp-signature/i) > 0) {
+    } else if (
+      contentType.search(/^multipart\/signed(;|$)/i) === 0 &&
+      contentType.search(/application\/pgp-signature/i) > 0
+    ) {
       this.movePEPsubject();
       this.messageDecryptCb(event, isAuto, null);
       return;
     }
 
     try {
-      EnigmailMime.getMimeTreeFromUrl(this.getCurrentMsgUrl().spec, false,
-        function _cb(mimeMsg) {
+      EnigmailMime.getMimeTreeFromUrl(
+        this.getCurrentMsgUrl().spec,
+        false,
+        function(mimeMsg) {
           Enigmail.msg.messageDecryptCb(event, isAuto, mimeMsg);
-        });
-    }
-    catch (ex) {
-      EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageDecrypt: exception: " + ex.toString() + "\n");
+        }
+      );
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "enigmailMessengerOverlay.js: messageDecrypt: exception: " +
+          ex.toString() +
+          "\n"
+      );
       this.messageDecryptCb(event, isAuto, null);
     }
   },
 
   /***
    * walk through the (sub-) mime tree and determine PGP/MIME encrypted and signed message parts
    *
    * @param mimePart:  parent object to walk through
    * @param resultObj: object containing two arrays. The resultObj must be pre-initialized by the caller
    *                    - encrypted
    *                    - signed
    */
-  enumerateMimeParts: function(mimePart, resultObj) {
-    EnigmailLog.DEBUG("enumerateMimeParts: partNum=\"" + mimePart.partNum + "\"\n");
+  enumerateMimeParts(mimePart, resultObj) {
+    EnigmailLog.DEBUG(
+      'enumerateMimeParts: partNum="' + mimePart.partNum + '"\n'
+    );
     EnigmailLog.DEBUG("                    " + mimePart.fullContentType + "\n");
-    EnigmailLog.DEBUG("                    " + mimePart.subParts.length + " subparts\n");
+    EnigmailLog.DEBUG(
+      "                    " + mimePart.subParts.length + " subparts\n"
+    );
 
     try {
       var ct = mimePart.fullContentType;
-      if (typeof(ct) == "string") {
+      if (typeof ct == "string") {
         ct = ct.replace(/[\r\n]/g, " ");
         if (ct.search(/multipart\/signed.*application\/pgp-signature/i) >= 0) {
           resultObj.signed.push(mimePart.partNum);
-        }
-        else if (ct.search(/application\/pgp-encrypted/i) >= 0) {
+        } else if (ct.search(/application\/pgp-encrypted/i) >= 0) {
           resultObj.encrypted.push(mimePart.partNum);
         }
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       // catch exception if no headers or no content-type defined.
     }
 
     var i;
     for (i in mimePart.subParts) {
       this.enumerateMimeParts(mimePart.subParts[i], resultObj);
     }
   },
 
-  messageDecryptCb: function(event, isAuto, mimeMsg) {
+  messageDecryptCb(event, isAuto, mimeMsg) {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageDecryptCb:\n");
 
     this.buggyExchangeEmailContent = null; // reinit HACK for MS-EXCHANGE-Server Problem
 
     let enigmailSvc;
     let contentType = "";
     try {
-
       if (!mimeMsg) {
-        EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageDecryptCb: mimeMsg is null\n");
+        EnigmailLog.DEBUG(
+          "enigmailMessengerOverlay.js: messageDecryptCb: mimeMsg is null\n"
+        );
         try {
-          contentType = currentHeaderData['content-type'].headerValue;
-        }
-        catch (ex) {
+          contentType = currentHeaderData["content-type"].headerValue;
+        } catch (ex) {
           contentType = "text/plain";
         }
         mimeMsg = {
           partNum: "1",
           headers: {
-            has: function() {
+            has() {
               return false;
             },
             contentType: {
               type: contentType,
               mediatype: "",
-              subtype: ""
-            }
+              subtype: "",
+            },
           },
           fullContentType: contentType,
           body: "",
           parent: null,
-          subParts: []
+          subParts: [],
         };
       }
 
       // Copy selected headers
       Enigmail.msg.savedHeaders = {
-        autocrypt: []
+        autocrypt: [],
       };
 
       for (let h in currentHeaderData) {
         if (h.search(/^autocrypt\d*$/) === 0) {
-          Enigmail.msg.savedHeaders.autocrypt.push(currentHeaderData[h].headerValue);
+          Enigmail.msg.savedHeaders.autocrypt.push(
+            currentHeaderData[h].headerValue
+          );
         }
       }
 
       if (!mimeMsg.fullContentType) {
         mimeMsg.fullContentType = "text/plain";
       }
 
       Enigmail.msg.savedHeaders["content-type"] = mimeMsg.fullContentType;
@@ -642,272 +783,381 @@ Enigmail.msg = {
       for (var index = 0; index < Enigmail.msg.headersList.length; index++) {
         var headerName = Enigmail.msg.headersList[index];
         var headerValue = "";
 
         if (mimeMsg.headers.has(headerName)) {
           let h = mimeMsg.headers.get(headerName);
           if (Array.isArray(h)) {
             headerValue = h.join("");
-          }
-          else {
+          } else {
             headerValue = h;
           }
         }
         Enigmail.msg.savedHeaders[headerName] = headerValue;
-        EnigmailLog.DEBUG("enigmailMessengerOverlay.js: header " + headerName + ": '" + headerValue + "'\n");
+        EnigmailLog.DEBUG(
+          "enigmailMessengerOverlay.js: header " +
+            headerName +
+            ": '" +
+            headerValue +
+            "'\n"
+        );
       }
 
-      if (("autocrypt" in Enigmail.msg.savedHeaders) && Enigmail.msg.savedHeaders.autocrypt.length > 0 &&
-        ("from" in currentHeaderData)) {
-
+      if (
+        "autocrypt" in Enigmail.msg.savedHeaders &&
+        Enigmail.msg.savedHeaders.autocrypt.length > 0 &&
+        "from" in currentHeaderData
+      ) {
         let dateValue = "";
         if ("date" in currentHeaderData) {
           dateValue = currentHeaderData.date.headerValue;
         }
 
-        EnigmailAutocrypt.processAutocryptHeader(currentHeaderData.from.headerValue, Enigmail.msg.savedHeaders.autocrypt,
-          dateValue, Enigmail.msg.isAutocryptEnabled());
-      }
-      else {
+        EnigmailAutocrypt.processAutocryptHeader(
+          currentHeaderData.from.headerValue,
+          Enigmail.msg.savedHeaders.autocrypt,
+          dateValue,
+          Enigmail.msg.isAutocryptEnabled()
+        );
+      } else {
         Enigmail.msg.createArtificialAutocryptHeader();
       }
 
-      var msgSigned = (mimeMsg.fullContentType.search(/^multipart\/signed/i) === 0 &&
-        EnigmailMime.getProtocol(mimeMsg.fullContentType).search(/^application\/pgp-signature/i) === 0);
-      var msgEncrypted = (mimeMsg.fullContentType.search(/^multipart\/encrypted/i) === 0 &&
-        EnigmailMime.getProtocol(mimeMsg.fullContentType).search(/^application\/pgp-encrypted/i) === 0);
+      var msgSigned =
+        mimeMsg.fullContentType.search(/^multipart\/signed/i) === 0 &&
+        EnigmailMime.getProtocol(mimeMsg.fullContentType).search(
+          /^application\/pgp-signature/i
+        ) === 0;
+      var msgEncrypted =
+        mimeMsg.fullContentType.search(/^multipart\/encrypted/i) === 0 &&
+        EnigmailMime.getProtocol(mimeMsg.fullContentType).search(
+          /^application\/pgp-encrypted/i
+        ) === 0;
       var resultObj = {
         encrypted: [],
-        signed: []
+        signed: [],
       };
 
       if (mimeMsg.subParts.length > 0) {
         this.enumerateMimeParts(mimeMsg, resultObj);
-        EnigmailLog.DEBUG("enigmailMessengerOverlay.js: embedded objects: " + resultObj.encrypted.join(", ") + " / " + resultObj.signed.join(", ") + "\n");
+        EnigmailLog.DEBUG(
+          "enigmailMessengerOverlay.js: embedded objects: " +
+            resultObj.encrypted.join(", ") +
+            " / " +
+            resultObj.signed.join(", ") +
+            "\n"
+        );
 
         msgSigned = msgSigned || resultObj.signed.length > 0;
         msgEncrypted = msgEncrypted || resultObj.encrypted.length > 0;
 
-        if ("autocrypt-setup-message" in Enigmail.msg.savedHeaders && Enigmail.msg.savedHeaders["autocrypt-setup-message"].toLowerCase() === "v1") {
-          if (currentAttachments[0].contentType.search(/^application\/autocrypt-setup$/i) === 0) {
+        if (
+          "autocrypt-setup-message" in Enigmail.msg.savedHeaders &&
+          Enigmail.msg.savedHeaders["autocrypt-setup-message"].toLowerCase() ===
+            "v1"
+        ) {
+          if (
+            currentAttachments[0].contentType.search(
+              /^application\/autocrypt-setup$/i
+            ) === 0
+          ) {
             Enigmail.hdrView.displayAutoCryptSetupMsgHeader();
             return;
           }
         }
 
         // HACK for Zimbra OpenPGP Zimlet
         // Zimbra illegally changes attachment content-type to application/pgp-encrypted which interfers with below
         // see https://sourceforge.net/p/enigmail/bugs/600/
 
         try {
-
-          if (mimeMsg.subParts.length > 1 &&
-            mimeMsg.headers.has("x-mailer") && mimeMsg.headers.get("x-mailer")[0].indexOf("ZimbraWebClient") >= 0 &&
-            mimeMsg.subParts[0].fullContentType.indexOf("text/plain") >= 0 &&
-            mimeMsg.fullContentType.indexOf("multipart/mixed") >= 0 &&
-            mimeMsg.subParts[1].fullContentType.indexOf("application/pgp-encrypted") >= 0) {
-            this.messageParse(event, false, Enigmail.msg.savedHeaders["content-transfer-encoding"], this.getCurrentMsgUriSpec(), isAuto);
+          if (
+            mimeMsg.subParts.length > 1 &&
+            mimeMsg.headers.has("x-mailer") &&
+            mimeMsg.headers.get("x-mailer")[0].includes("ZimbraWebClient") &&
+            mimeMsg.subParts[0].fullContentType.includes("text/plain") &&
+            mimeMsg.fullContentType.includes("multipart/mixed") &&
+            mimeMsg.subParts[1].fullContentType.includes(
+              "application/pgp-encrypted"
+            )
+          ) {
+            this.messageParse(
+              event,
+              false,
+              Enigmail.msg.savedHeaders["content-transfer-encoding"],
+              this.getCurrentMsgUriSpec(),
+              isAuto
+            );
             return;
           }
-        }
-        catch (ex) {}
-
+        } catch (ex) {}
 
         // HACK for MS-EXCHANGE-Server Problem:
         // check for possible bad mime structure due to buggy exchange server:
         // - multipart/mixed Container with
         //   - application/pgp-encrypted Attachment with name "PGPMIME Versions Identification"
         //   - application/octet-stream Attachment with name "encrypted.asc" having the encrypted content in base64
         // - see:
         //   - http://www.mozilla-enigmail.org/forum/viewtopic.php?f=4&t=425
         //   - http://sourceforge.net/p/enigmail/forum/support/thread/4add2b69/
 
         // iPGMail produces a similar broken structure, see here:
         //   - https://sourceforge.net/p/enigmail/forum/support/thread/afc9c246/#5de7
 
-        if (mimeMsg.subParts.length == 3 &&
+        if (
+          mimeMsg.subParts.length == 3 &&
           mimeMsg.fullContentType.search(/multipart\/mixed/i) >= 0 &&
-          mimeMsg.subParts[0].fullContentType.search(/multipart\/encrypted/i) < 0 &&
-          mimeMsg.subParts[0].fullContentType.search(/text\/(plain|html)/i) >= 0 &&
-          mimeMsg.subParts[1].fullContentType.search(/application\/pgp-encrypted/i) >= 0) {
-          if (mimeMsg.subParts[1].fullContentType.search(/multipart\/encrypted/i) < 0 &&
-            mimeMsg.subParts[1].fullContentType.search(/PGP\/?MIME Versions? Identification/i) >= 0 &&
-            mimeMsg.subParts[2].fullContentType.search(/application\/octet-stream/i) >= 0 &&
-            mimeMsg.subParts[2].fullContentType.search(/encrypted.asc/i) >= 0) {
+          mimeMsg.subParts[0].fullContentType.search(/multipart\/encrypted/i) <
+            0 &&
+          mimeMsg.subParts[0].fullContentType.search(/text\/(plain|html)/i) >=
+            0 &&
+          mimeMsg.subParts[1].fullContentType.search(
+            /application\/pgp-encrypted/i
+          ) >= 0
+        ) {
+          if (
+            mimeMsg.subParts[1].fullContentType.search(
+              /multipart\/encrypted/i
+            ) < 0 &&
+            mimeMsg.subParts[1].fullContentType.search(
+              /PGP\/?MIME Versions? Identification/i
+            ) >= 0 &&
+            mimeMsg.subParts[2].fullContentType.search(
+              /application\/octet-stream/i
+            ) >= 0 &&
+            mimeMsg.subParts[2].fullContentType.search(/encrypted.asc/i) >= 0
+          ) {
             this.buggyMailType = "exchange";
-          }
-          else {
+          } else {
             this.buggyMailType = "iPGMail";
           }
 
           // signal that the structure matches to save the content later on
-          EnigmailLog.DEBUG("enigmailMessengerOverlay: messageDecryptCb: enabling MS-Exchange hack\n");
+          EnigmailLog.DEBUG(
+            "enigmailMessengerOverlay: messageDecryptCb: enabling MS-Exchange hack\n"
+          );
           this.buggyExchangeEmailContent = "???";
 
           this.buggyMailHeader();
           return;
         }
       }
 
       var contentEncoding = "";
-      var xEnigmailVersion = "";
       var msgUriSpec = this.getCurrentMsgUriSpec();
 
       if (Enigmail.msg.savedHeaders) {
         contentType = Enigmail.msg.savedHeaders["content-type"];
-        contentEncoding = Enigmail.msg.savedHeaders["content-transfer-encoding"];
-        xEnigmailVersion = Enigmail.msg.savedHeaders["x-enigmail-version"];
+        contentEncoding =
+          Enigmail.msg.savedHeaders["content-transfer-encoding"];
       }
 
-      let smime = (contentType.search(/multipart\/signed; protocol="application\/pkcs7-signature/i) >= 0);
+      let smime =
+        contentType.search(
+          /multipart\/signed; protocol="application\/pkcs7-signature/i
+        ) >= 0;
       if (!smime && (msgSigned || msgEncrypted)) {
         // PGP/MIME messages
         enigmailSvc = Enigmail.getEnigmailSvc();
         if (!enigmailSvc) {
           return;
         }
 
         if (!Enigmail.msg.checkPgpmimeHandler()) {
           return;
         }
 
-        if (isAuto && (!EnigmailPrefs.getPref("autoDecrypt"))) {
-
+        if (isAuto && !EnigmailPrefs.getPref("autoDecrypt")) {
           if (EnigmailVerify.getManualUri() != this.getCurrentMsgUriSpec()) {
             // decryption set to manual
-            Enigmail.hdrView.updateHdrIcons(EnigmailConstants.POSSIBLE_PGPMIME, 0, // exitCode, statusFlags
-              "", "", // keyId, userId
+            Enigmail.hdrView.updateHdrIcons(
+              EnigmailConstants.POSSIBLE_PGPMIME,
+              0, // exitCode, statusFlags
+              "",
+              "", // keyId, userId
               "", // sigDetails
               EnigmailLocale.getString("possiblyPgpMime"), // infoMsg
               null, // blockSeparation
               "", // encToDetails
-              null); // xtraStatus
+              null
+            ); // xtraStatus
           }
-        }
-        else if (!isAuto) {
+        } else if (!isAuto) {
           Enigmail.msg.messageReload(false);
         }
         return;
       }
 
       // inline-PGP messages
       if (!isAuto || EnigmailPrefs.getPref("autoDecrypt")) {
         this.messageParse(event, false, contentEncoding, msgUriSpec, isAuto);
       }
-    }
-    catch (ex) {
-      EnigmailLog.writeException("enigmailMessengerOverlay.js: messageDecryptCb", ex);
+    } catch (ex) {
+      EnigmailLog.writeException(
+        "enigmailMessengerOverlay.js: messageDecryptCb",
+        ex
+      );
     }
   },
 
   // display header about reparing buggy MS-Exchange messages
-  buggyMailHeader: function() {
-    let uriStr = EnigmailURIs.createMessageURI(this.getCurrentMsgUrl(),
+  buggyMailHeader() {
+    let uriStr = EnigmailURIs.createMessageURI(
+      this.getCurrentMsgUrl(),
       "message/rfc822",
       "",
       "??",
-      false);
+      false
+    );
 
     let ph = new EnigmailProtocolHandler();
-    let uri = ph.newURI(uriStr, "", "");
-    Enigmail.hdrView.headerPane.updateSecurityStatus("", 0, 0, "", "", "", "", "", uri, "", "1");
+    let uri = ph.newURI(uriStr);
+    Enigmail.hdrView.headerPane.updateSecurityStatus(
+      "",
+      0,
+      0,
+      "",
+      "",
+      "",
+      "",
+      "",
+      uri,
+      "",
+      "1"
+    );
   },
 
-  messageParse: function(interactive, importOnly, contentEncoding, msgUriSpec, isAuto, pbMessageIndex = '0') {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParse: " + interactive + "\n");
+  messageParse(
+    interactive,
+    importOnly,
+    contentEncoding,
+    msgUriSpec,
+    isAuto,
+    pbMessageIndex = "0"
+  ) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: messageParse: " + interactive + "\n"
+    );
 
     var bodyElement = this.getBodyElement(pbMessageIndex);
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: bodyElement=" + bodyElement + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: bodyElement=" + bodyElement + "\n"
+    );
 
     if (!bodyElement) {
       return;
     }
 
     let topElement = bodyElement;
     var findStr = /* interactive ? null : */ "-----BEGIN PGP";
     var msgText = null;
     var foundIndex = -1;
 
     if (bodyElement.firstChild) {
       let node = bodyElement.firstChild;
       while (node) {
-        if (node.firstChild &&
+        if (
+          node.firstChild &&
           node.firstChild.nodeName == "LEGEND" &&
-          node.firstChild.className == "mimeAttachmentHeaderName") {
+          node.firstChild.className == "mimeAttachmentHeaderName"
+        ) {
           // we reached the area where inline attachments are displayed
           // --> don't try to decrypt displayed inline attachments
           break;
         }
-        if (node.firstChild &&
+        if (
+          node.firstChild &&
           node.firstChild.nodeName.toUpperCase() == "LEGEND" &&
-          node.firstChild.className == "mimeAttachmentHeaderName") {
+          node.firstChild.className == "mimeAttachmentHeaderName"
+        ) {
           // we reached the area where inline attachments are displayed
           // --> don't try to decrypt displayed inline attachments
           break;
         }
         if (node.nodeName === "DIV") {
           foundIndex = node.textContent.indexOf(findStr);
 
           if (foundIndex >= 0) {
-            if (node.textContent.indexOf(findStr + " LICENSE AUTHORIZATION") == foundIndex) {
+            if (
+              node.textContent.indexOf(findStr + " LICENSE AUTHORIZATION") ==
+              foundIndex
+            ) {
               foundIndex = -1;
             }
           }
 
           if (foundIndex === 0) {
             bodyElement = node;
             break;
           }
-          if (foundIndex > 0 && node.textContent.substr(foundIndex - 1, 1).search(/[\r\n]/) === 0) {
+          if (
+            foundIndex > 0 &&
+            node.textContent.substr(foundIndex - 1, 1).search(/[\r\n]/) === 0
+          ) {
             bodyElement = node;
             break;
           }
         }
         node = node.nextSibling;
       }
     }
 
-    if (foundIndex >= 0 && (!this.hasInlineQuote(topElement))) {
-      if (Enigmail.msg.savedHeaders["content-type"].search(/^text\/html/i) === 0) {
-        let p = Cc["@mozilla.org/parserutils;1"].createInstance(Ci.nsIParserUtils);
+    if (foundIndex >= 0 && !this.hasInlineQuote(topElement)) {
+      if (
+        Enigmail.msg.savedHeaders["content-type"].search(/^text\/html/i) === 0
+      ) {
+        let p = Cc["@mozilla.org/parserutils;1"].createInstance(
+          Ci.nsIParserUtils
+        );
         const de = Ci.nsIDocumentEncoder;
-        msgText = p.convertToPlainText(topElement.innerHTML, de.OutputRaw | de.OutputBodyOnly, 0);
-      }
-      else {
+        msgText = p.convertToPlainText(
+          topElement.innerHTML,
+          de.OutputRaw | de.OutputBodyOnly,
+          0
+        );
+      } else {
         msgText = bodyElement.textContent;
       }
       msgText = EnigmailMsgRead.trimAllLines(msgText);
     }
 
     if (!msgText) {
       // No PGP content
 
       // but this might be caused by the HACK for MS-EXCHANGE-Server Problem
       // - so return only if:
-      if (!this.buggyExchangeEmailContent || this.buggyExchangeEmailContent == "???") {
+      if (
+        !this.buggyExchangeEmailContent ||
+        this.buggyExchangeEmailContent == "???"
+      ) {
         return;
       }
 
-      EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParse: got buggyExchangeEmailContent = " + this.buggyExchangeEmailContent.substr(0, 50) + "\n");
+      EnigmailLog.DEBUG(
+        "enigmailMessengerOverlay.js: messageParse: got buggyExchangeEmailContent = " +
+          this.buggyExchangeEmailContent.substr(0, 50) +
+          "\n"
+      );
 
       // fix the whole invalid email by replacing the contents by the decoded text
       // as plain inline format
       if (this.displayBuggyExchangeMail()) {
         return;
       }
-      else {
-        msgText = this.buggyExchangeEmailContent;
-      }
+
+      msgText = this.buggyExchangeEmailContent;
 
       msgText = msgText.replace(/\r\n/g, "\n");
       msgText = msgText.replace(/\r/g, "\n");
 
       // content is in encrypted.asc part:
-      let idx = msgText.search(/Content-Type: application\/octet-stream; name="encrypted.asc"/i);
+      let idx = msgText.search(
+        /Content-Type: application\/octet-stream; name="encrypted.asc"/i
+      );
       if (idx >= 0) {
         msgText = msgText.slice(idx);
       }
       // check whether we have base64 encoding
       var isBase64 = false;
       idx = msgText.search(/Content-Transfer-Encoding: base64/i);
       if (idx >= 0) {
         isBase64 = true;
@@ -921,43 +1171,59 @@ Enigmail.msg = {
       idx = msgText.search(/\n\n--/);
       if (idx >= 0) {
         msgText = msgText.slice(0, idx + 1);
       }
       // decode base64 if it is encoded that way
       if (isBase64) {
         try {
           msgText = EnigmailData.decodeBase64(msgText);
-        }
-        catch (ex) {
-          EnigmailLog.writeException("enigmailMessengerOverlay.js: decodeBase64() ", ex);
+        } catch (ex) {
+          EnigmailLog.writeException(
+            "enigmailMessengerOverlay.js: decodeBase64() ",
+            ex
+          );
         }
         //EnigmailLog.DEBUG("nach base64 decode: \n" + msgText + "\n");
       }
     }
 
     var charset = msgWindow ? msgWindow.mailCharacterSet : "";
 
     // Encode ciphertext to charset from unicode
     msgText = EnigmailData.convertFromUnicode(msgText, charset);
 
     if (isAuto) {
       let ht = this.determineHeadAndTail(msgText);
       if (ht) {
-        Enigmail.hdrView.updateHdrIcons(0, ht, "", "", "", "", null, "", "process-manually");
+        Enigmail.hdrView.updateHdrIcons(
+          0,
+          ht,
+          "",
+          "",
+          "",
+          "",
+          null,
+          "",
+          "process-manually"
+        );
         return;
       }
     }
     var mozPlainText = bodyElement.innerHTML.search(/class="moz-text-plain"/);
 
-    if ((mozPlainText >= 0) && (mozPlainText < 40)) {
+    if (mozPlainText >= 0 && mozPlainText < 40) {
       // workaround for too much expanded emoticons in plaintext msg
-      var r = new RegExp(/( )(;-\)|:-\)|;\)|:\)|:-\(|:\(|:-\\|:-P|:-D|:-\[|:-\*|>:o|8-\)|:-\$|:-X|=-O|:-!|O:-\)|:'\()( )/g);
+      var r = new RegExp(
+        /( )(;-\)|:-\)|;\)|:\)|:-\(|:\(|:-\\|:-P|:-D|:-\[|:-\*|>:o|8-\)|:-\$|:-X|=-O|:-!|O:-\)|:'\()( )/g
+      );
       if (msgText.search(r) >= 0) {
-        EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParse: performing emoticons fixing\n");
+        EnigmailLog.DEBUG(
+          "enigmailMessengerOverlay.js: messageParse: performing emoticons fixing\n"
+        );
         msgText = msgText.replace(r, "$2");
       }
     }
 
     // extract text following armored block
     var head = "";
     var tail = "";
     if (findStr) {
@@ -969,257 +1235,357 @@ Enigmail.msg = {
     }
 
     //EnigmailLog.DEBUG("enigmailMessengerOverlay.js: msgText='"+msgText+"'\n");
 
     var mailNewsUrl = EnigmailMsgRead.getUrlFromUriSpec(msgUriSpec);
 
     var urlSpec = mailNewsUrl ? mailNewsUrl.spec : "";
 
-    let retry = (charset != "UTF-8" ? 1 : 2);
-
-    Enigmail.msg.messageParseCallback(msgText, contentEncoding, charset, interactive,
-      importOnly, urlSpec, "", retry, head, tail,
-      msgUriSpec, isAuto, pbMessageIndex);
+    let retry = charset != "UTF-8" ? 1 : 2;
+
+    Enigmail.msg.messageParseCallback(
+      msgText,
+      contentEncoding,
+      charset,
+      interactive,
+      importOnly,
+      urlSpec,
+      "",
+      retry,
+      head,
+      tail,
+      msgUriSpec,
+      isAuto,
+      pbMessageIndex
+    );
   },
 
-  hasInlineQuote: function(node) {
+  hasInlineQuote(node) {
     if (node.innerHTML.search(/<blockquote.*-----BEGIN PGP /i) < 0) {
       return false;
     }
 
     return EnigmailMsgRead.searchQuotedPgp(node);
   },
 
-  determineHeadAndTail: function(msgText) {
+  determineHeadAndTail(msgText) {
     let startIndex = msgText.search(/-----BEGIN PGP (SIGNED )?MESSAGE-----/m);
     let endIndex = msgText.indexOf("-----END PGP");
     let hasHead = false;
     let hasTail = false;
     let crypto = 0;
 
     if (startIndex > 0) {
       let pgpMsg = msgText.match(/(-----BEGIN PGP (SIGNED )?MESSAGE-----)/m)[0];
       if (pgpMsg.search(/SIGNED/) > 0) {
         crypto = EnigmailConstants.UNVERIFIED_SIGNATURE;
-      }
-      else {
+      } else {
         crypto = EnigmailConstants.DECRYPTION_FAILED;
       }
       let startSection = msgText.substr(0, startIndex - 1);
-      hasHead = (startSection.search(/\S/) >= 0);
+      hasHead = startSection.search(/\S/) >= 0;
     }
 
     if (endIndex > startIndex) {
       let nextLine = msgText.substring(endIndex).search(/[\n\r]/);
       if (nextLine > 0) {
-        hasTail = (msgText.substring(endIndex + nextLine).search(/\S/) >= 0);
+        hasTail = msgText.substring(endIndex + nextLine).search(/\S/) >= 0;
       }
     }
 
     if (hasHead || hasTail) {
       return EnigmailConstants.PARTIALLY_PGP | crypto;
     }
 
     return 0;
   },
 
-  getBodyElement: function(pbMessageIndex = '0') {
+  getBodyElement(pbMessageIndex = "0") {
     let bodyElement = null;
 
     // Thunderbird
     let msgFrame = EnigmailWindows.getFrame(window, "messagepane");
     if (msgFrame) {
       // TB < 69
       bodyElement = msgFrame.document.getElementsByTagName("body")[0];
-    }
-    else {
+    } else {
       // TB >= 69
-      msgFrame = document.getElementById('messagepane');
+      msgFrame = document.getElementById("messagepane");
       bodyElement = msgFrame.contentDocument.getElementsByTagName("body")[0];
     }
     return bodyElement;
   },
 
-
-  messageParseCallback: function(msgText, contentEncoding, charset, interactive,
-    importOnly, messageUrl, signature, retry, head, tail, msgUriSpec, isAuto,
-    pbMessageIndex) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParseCallback: " + interactive + ", " + interactive + ", importOnly=" + importOnly + ", charset=" + charset + ", msgUrl=" +
-      messageUrl +
-      ", retry=" + retry + ", signature='" + signature + "'\n");
+  messageParseCallback(
+    msgText,
+    contentEncoding,
+    charset,
+    interactive,
+    importOnly,
+    messageUrl,
+    signature,
+    retry,
+    head,
+    tail,
+    msgUriSpec,
+    isAuto,
+    pbMessageIndex
+  ) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: messageParseCallback: " +
+        interactive +
+        ", " +
+        interactive +
+        ", importOnly=" +
+        importOnly +
+        ", charset=" +
+        charset +
+        ", msgUrl=" +
+        messageUrl +
+        ", retry=" +
+        retry +
+        ", signature='" +
+        signature +
+        "'\n"
+    );
 
     if (!msgText) {
       return;
     }
 
     var enigmailSvc = Enigmail.getEnigmailSvc();
     if (!enigmailSvc) {
       return;
     }
 
     var plainText;
     var exitCode;
     var newSignature = "";
     var statusFlags = 0;
 
     var errorMsgObj = {
-      value: ""
+      value: "",
     };
     var keyIdObj = {};
     var userIdObj = {};
     var sigDetailsObj = {};
     var encToDetailsObj = {};
 
     var blockSeparationObj = {
-      value: ""
+      value: "",
     };
 
     if (importOnly) {
       // Import public key
       this.importKeyFromMsgBody(msgText);
       return;
     }
-    else {
-
-      let armorHeaders = EnigmailArmor.getArmorHeaders(msgText);
-      if ("charset" in armorHeaders) {
-        charset = armorHeaders.charset;
-        EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParseCallback: OVERRIDING charset=" + charset + "\n");
-      }
-
-      var exitCodeObj = {};
-      var statusFlagsObj = {};
-      var signatureObj = {};
-      signatureObj.value = signature;
-
-      var uiFlags = interactive ? (EnigmailConstants.UI_INTERACTIVE |
+    let armorHeaders = EnigmailArmor.getArmorHeaders(msgText);
+    if ("charset" in armorHeaders) {
+      charset = armorHeaders.charset;
+      EnigmailLog.DEBUG(
+        "enigmailMessengerOverlay.js: messageParseCallback: OVERRIDING charset=" +
+          charset +
+          "\n"
+      );
+    }
+
+    var exitCodeObj = {};
+    var statusFlagsObj = {};
+    var signatureObj = {};
+    signatureObj.value = signature;
+
+    var uiFlags = interactive
+      ? EnigmailConstants.UI_INTERACTIVE |
         EnigmailConstants.UI_ALLOW_KEY_IMPORT |
-        EnigmailConstants.UI_UNVERIFIED_ENC_OK) : 0;
-
-      plainText = EnigmailDecryption.decryptMessage(window, uiFlags, msgText,
-        signatureObj, exitCodeObj, statusFlagsObj,
-        keyIdObj, userIdObj, sigDetailsObj,
-        errorMsgObj, blockSeparationObj, encToDetailsObj);
-
-      //EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParseCallback: plainText='"+plainText+"'\n");
-
-      exitCode = exitCodeObj.value;
-      newSignature = signatureObj.value;
-
-      if (plainText === "" && exitCode === 0) {
-        plainText = " ";
-      }
-
-      statusFlags = statusFlagsObj.value;
-
-      EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParseCallback: newSignature='" + newSignature + "'\n");
+        EnigmailConstants.UI_UNVERIFIED_ENC_OK
+      : 0;
+
+    plainText = EnigmailDecryption.decryptMessage(
+      window,
+      uiFlags,
+      msgText,
+      signatureObj,
+      exitCodeObj,
+      statusFlagsObj,
+      keyIdObj,
+      userIdObj,
+      sigDetailsObj,
+      errorMsgObj,
+      blockSeparationObj,
+      encToDetailsObj
+    );
+
+    //EnigmailLog.DEBUG("enigmailMessengerOverlay.js: messageParseCallback: plainText='"+plainText+"'\n");
+
+    exitCode = exitCodeObj.value;
+    newSignature = signatureObj.value;
+
+    if (plainText === "" && exitCode === 0) {
+      plainText = " ";
     }
 
+    statusFlags = statusFlagsObj.value;
+
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: messageParseCallback: newSignature='" +
+        newSignature +
+        "'\n"
+    );
+
     var errorMsg = errorMsgObj.value;
 
     if (importOnly) {
       if (interactive && errorMsg) {
         EnigmailDialog.alert(window, errorMsg);
       }
       return;
     }
 
     var displayedUriSpec = Enigmail.msg.getCurrentMsgUriSpec();
-    if (!msgUriSpec || (displayedUriSpec == msgUriSpec)) {
+    if (!msgUriSpec || displayedUriSpec == msgUriSpec) {
       if (tail.length > 0) {
         statusFlags |= EnigmailConstants.PARTIALLY_PGP;
       }
-      Enigmail.hdrView.updateHdrIcons(exitCode, statusFlags, keyIdObj.value, userIdObj.value,
+      Enigmail.hdrView.updateHdrIcons(
+        exitCode,
+        statusFlags,
+        keyIdObj.value,
+        userIdObj.value,
         sigDetailsObj.value,
         errorMsg,
         null, // blockSeparation
         encToDetailsObj.value,
-        null); // xtraStatus
+        null
+      ); // xtraStatus
     }
 
-    var noSecondTry = EnigmailConstants.GOOD_SIGNATURE |
+    var noSecondTry =
+      EnigmailConstants.GOOD_SIGNATURE |
       EnigmailConstants.EXPIRED_SIGNATURE |
       EnigmailConstants.EXPIRED_KEY_SIGNATURE |
       EnigmailConstants.EXPIRED_KEY |
       EnigmailConstants.REVOKED_KEY |
       EnigmailConstants.NO_PUBKEY |
       EnigmailConstants.NO_SECKEY |
       EnigmailConstants.IMPORTED_KEY |
       EnigmailConstants.MISSING_PASSPHRASE |
       EnigmailConstants.BAD_PASSPHRASE |
       EnigmailConstants.UNKNOWN_ALGO |
       EnigmailConstants.DECRYPTION_OKAY |
       EnigmailConstants.OVERFLOWED;
 
-    if ((exitCode !== 0) && (!(statusFlags & noSecondTry))) {
+    if (exitCode !== 0 && !(statusFlags & noSecondTry)) {
       // Bad signature/armor
       if (retry == 1) {
         msgText = EnigmailData.convertFromUnicode(msgText, "UTF-8");
-        Enigmail.msg.messageParseCallback(msgText, contentEncoding, charset,
-          interactive, importOnly, messageUrl,
-          signature, retry + 1,
-          head, tail, msgUriSpec, isAuto, pbMessageIndex);
+        Enigmail.msg.messageParseCallback(
+          msgText,
+          contentEncoding,
+          charset,
+          interactive,
+          importOnly,
+          messageUrl,
+          signature,
+          retry + 1,
+          head,
+          tail,
+          msgUriSpec,
+          isAuto,
+          pbMessageIndex
+        );
         return;
-      }
-      else if (retry == 2) {
+      } else if (retry == 2) {
         // Try to verify signature by accessing raw message text directly
         // (avoid recursion by setting retry parameter to false on callback)
         newSignature = "";
-        Enigmail.msg.msgDirectDecrypt(interactive, importOnly, contentEncoding, charset,
-          newSignature, 0, head, tail, msgUriSpec,
-          Enigmail.msg.messageParseCallback, isAuto);
+        Enigmail.msg.msgDirectDecrypt(
+          interactive,
+          importOnly,
+          contentEncoding,
+          charset,
+          newSignature,
+          0,
+          head,
+          tail,
+          msgUriSpec,
+          Enigmail.msg.messageParseCallback,
+          isAuto
+        );
         return;
-      }
-      else if (retry == 3) {
+      } else if (retry == 3) {
         msgText = EnigmailData.convertToUnicode(msgText, "UTF-8");
-        Enigmail.msg.messageParseCallback(msgText, contentEncoding, charset, interactive,
-          importOnly, messageUrl, null, retry + 1,
-          head, tail, msgUriSpec, isAuto, pbMessageIndex);
+        Enigmail.msg.messageParseCallback(
+          msgText,
+          contentEncoding,
+          charset,
+          interactive,
+          importOnly,
+          messageUrl,
+          null,
+          retry + 1,
+          head,
+          tail,
+          msgUriSpec,
+          isAuto,
+          pbMessageIndex
+        );
         return;
       }
     }
 
     if (!plainText) {
-      if (interactive && Enigmail.msg.securityInfo && Enigmail.msg.securityInfo.statusInfo) {
+      if (
+        interactive &&
+        Enigmail.msg.securityInfo &&
+        Enigmail.msg.securityInfo.statusInfo
+      ) {
         EnigmailDialog.info(window, Enigmail.msg.securityInfo.statusInfo);
       }
       return;
     }
 
     if (retry >= 2) {
-      plainText = EnigmailData.convertFromUnicode(EnigmailData.convertToUnicode(plainText, "UTF-8"), charset);
+      plainText = EnigmailData.convertFromUnicode(
+        EnigmailData.convertToUnicode(plainText, "UTF-8"),
+        charset
+      );
     }
 
-    if (blockSeparationObj.value.indexOf(" ") >= 0) {
+    if (blockSeparationObj.value.includes(" ")) {
       var blocks = blockSeparationObj.value.split(/ /);
       var blockInfo = blocks[0].split(/:/);
-      plainText = EnigmailData.convertFromUnicode(EnigmailLocale.getString("notePartEncrypted"), charset) +
-        "\n\n" + plainText.substr(0, blockInfo[1]) + "\n\n" + EnigmailLocale.getString("noteCutMessage");
+      plainText =
+        EnigmailData.convertFromUnicode(
+          EnigmailLocale.getString("notePartEncrypted"),
+          charset
+        ) +
+        "\n\n" +
+        plainText.substr(0, blockInfo[1]) +
+        "\n\n" +
+        EnigmailLocale.getString("noteCutMessage");
     }
 
     // Save decrypted message status, headers, and content
     var headerList = {
-      "subject": "",
-      "from": "",
-      "date": "",
-      "to": "",
-      "cc": ""
+      subject: "",
+      from: "",
+      date: "",
+      to: "",
+      cc: "",
     };
 
-    var index,
-      headerName;
+    var index, headerName;
 
     if (!gViewAllHeaders) {
       for (index = 0; index < headerList.length; index++) {
         headerList[index] = "";
       }
-
-    }
-    else {
+    } else {
       for (index = 0; index < gExpandedHeaderList.length; index++) {
         headerList[gExpandedHeaderList[index].name] = "";
       }
 
       for (headerName in currentHeaderData) {
         headerList[headerName] = "";
       }
     }
@@ -1235,203 +1601,263 @@ Enigmail.msg = {
       headerList.cc = "";
     }
 
     var hasAttachments = currentAttachments && currentAttachments.length;
     var attachmentsEncrypted = true;
 
     for (index in currentAttachments) {
       if (!Enigmail.msg.checkEncryptedAttach(currentAttachments[index])) {
-        if (!EnigmailMsgRead.checkSignedAttachment(currentAttachments, index, currentAttachments)) {
+        if (
+          !EnigmailMsgRead.checkSignedAttachment(
+            currentAttachments,
+            index,
+            currentAttachments
+          )
+        ) {
           attachmentsEncrypted = false;
         }
       }
     }
 
     var msgRfc822Text = "";
     if (tail) {
-      msgRfc822Text += EnigmailData.convertFromUnicode(EnigmailLocale.getString("beginPgpPart"), charset) + "\n\n";
+      msgRfc822Text +=
+        EnigmailData.convertFromUnicode(
+          EnigmailLocale.getString("beginPgpPart"),
+          charset
+        ) + "\n\n";
     }
     msgRfc822Text += plainText;
     if (tail) {
-      msgRfc822Text += "\n\n" + EnigmailData.convertFromUnicode(EnigmailLocale.getString("endPgpPart"), charset) + "\n\n" + tail;
+      msgRfc822Text +=
+        "\n\n" +
+        EnigmailData.convertFromUnicode(
+          EnigmailLocale.getString("endPgpPart"),
+          charset
+        ) +
+        "\n\n" +
+        tail;
     }
 
     Enigmail.msg.decryptedMessage = {
       url: messageUrl,
       uri: msgUriSpec,
-      headerList: headerList,
-      hasAttachments: hasAttachments,
-      attachmentsEncrypted: attachmentsEncrypted,
-      charset: charset,
-      plainText: msgRfc822Text
+      headerList,
+      hasAttachments,
+      attachmentsEncrypted,
+      charset,
+      plainText: msgRfc822Text,
     };
 
     // don't display decrypted message if message selection has changed
     displayedUriSpec = Enigmail.msg.getCurrentMsgUriSpec();
-    if (msgUriSpec && displayedUriSpec && (displayedUriSpec != msgUriSpec)) {
+    if (msgUriSpec && displayedUriSpec && displayedUriSpec != msgUriSpec) {
       return;
     }
 
-
     // Create and load one-time message URI
-    var messageContent = Enigmail.msg.getDecryptedMessage("message/rfc822", false);
+    var messageContent = Enigmail.msg.getDecryptedMessage(
+      "message/rfc822",
+      false
+    );
 
     Enigmail.msg.noShowReload = true;
     var node;
     var bodyElement = Enigmail.msg.getBodyElement(pbMessageIndex);
 
     if (bodyElement.firstChild) {
       node = bodyElement.firstChild;
 
       while (node) {
         if (node.nodeName == "DIV") {
           // for safety reasons, we replace the complete visible message with
           // the decrypted or signed part (bug 983)
-          node.innerHTML = EnigmailFuncs.formatPlaintextMsg(EnigmailData.convertToUnicode(messageContent, charset));
+          node.innerHTML = EnigmailFuncs.formatPlaintextMsg(
+            EnigmailData.convertToUnicode(messageContent, charset)
+          );
           Enigmail.msg.movePEPsubject();
           return;
         }
         node = node.nextSibling;
       }
 
       // if no <DIV> node is found, try with <PRE> (bug 24762)
       node = bodyElement.firstChild;
       while (node) {
         if (node.nodeName == "PRE") {
-          node.innerHTML = EnigmailFuncs.formatPlaintextMsg(EnigmailData.convertToUnicode(messageContent, charset));
+          node.innerHTML = EnigmailFuncs.formatPlaintextMsg(
+            EnigmailData.convertToUnicode(messageContent, charset)
+          );
           Enigmail.msg.movePEPsubject();
           return;
         }
         node = node.nextSibling;
       }
 
       // HACK for MS-EXCHANGE-Server Problem:
       // - remove empty text/plain part
       //   and set message content as inner text
       // - missing:
       //   - signal in statusFlags so that we warn in Enigmail.hdrView.updateHdrIcons()
       if (this.buggyExchangeEmailContent) {
         if (this.displayBuggyExchangeMail()) {
           return;
         }
 
-        EnigmailLog.DEBUG("enigmailMessengerOverlay: messageParseCallback: got broken MS-Exchange mime message\n");
-        messageContent = messageContent.replace(/^\s{0,2}Content-Transfer-Encoding: quoted-printable\s*Content-Type: text\/plain;\s*charset=windows-1252/i, "");
+        EnigmailLog.DEBUG(
+          "enigmailMessengerOverlay: messageParseCallback: got broken MS-Exchange mime message\n"
+        );
+        messageContent = messageContent.replace(
+          /^\s{0,2}Content-Transfer-Encoding: quoted-printable\s*Content-Type: text\/plain;\s*charset=windows-1252/i,
+          ""
+        );
         node = bodyElement.firstChild;
         while (node) {
           if (node.nodeName == "DIV") {
-            node.innerHTML = EnigmailFuncs.formatPlaintextMsg(EnigmailData.convertToUnicode(messageContent, charset));
-            Enigmail.hdrView.updateHdrIcons(exitCode, statusFlags, keyIdObj.value, userIdObj.value,
+            node.innerHTML = EnigmailFuncs.formatPlaintextMsg(
+              EnigmailData.convertToUnicode(messageContent, charset)
+            );
+            Enigmail.hdrView.updateHdrIcons(
+              exitCode,
+              statusFlags,
+              keyIdObj.value,
+              userIdObj.value,
               sigDetailsObj.value,
               errorMsg,
               null, // blockSeparation
               encToDetailsObj.value,
-              "buggyMailFormat");
+              "buggyMailFormat"
+            );
             return;
           }
           node = node.nextSibling;
         }
       }
-
     }
 
-    EnigmailLog.ERROR("enigmailMessengerOverlay.js: no node found to replace message display\n");
-
-    return;
+    EnigmailLog.ERROR(
+      "enigmailMessengerOverlay.js: no node found to replace message display\n"
+    );
   },
 
-  importKeyFromMsgBody: function(msgData) {
+  importKeyFromMsgBody(msgData) {
     let beginIndexObj = {};
     let endIndexObj = {};
     let indentStrObj = {};
-    let blockType = EnigmailArmor.locateArmoredBlock(msgData, 0, "", beginIndexObj, endIndexObj, indentStrObj);
+    let blockType = EnigmailArmor.locateArmoredBlock(
+      msgData,
+      0,
+      "",
+      beginIndexObj,
+      endIndexObj,
+      indentStrObj
+    );
     if (!blockType || blockType !== "PUBLIC KEY BLOCK") {
       return;
     }
 
     let keyData = msgData.substring(beginIndexObj.value, endIndexObj.value);
 
     let errorMsgObj = {};
     let preview = EnigmailKey.getKeyListFromKeyBlock(keyData, errorMsgObj);
     if (errorMsgObj.value === "") {
       this.importKeyDataWithConfirmation(preview, keyData);
-    }
-    else {
-      EnigmailDialog.alert(window, EnigmailLocale.getString("previewFailed") + "\n" + errorMsgObj.value);
+    } else {
+      EnigmailDialog.alert(
+        window,
+        EnigmailLocale.getString("previewFailed") + "\n" + errorMsgObj.value
+      );
     }
   },
 
-  importKeyDataWithConfirmation: function(preview, keyData) {
+  importKeyDataWithConfirmation(preview, keyData) {
     let exitStatus = -1,
       errorMsgObj = {};
     if (preview.length > 0) {
       if (preview.length == 1) {
-        exitStatus = EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("doImportOne", [preview[0].name, preview[0].id]));
-      }
-      else {
-        exitStatus = EnigmailDialog.confirmDlg(window,
+        exitStatus = EnigmailDialog.confirmDlg(
+          window,
+          EnigmailLocale.getString("doImportOne", [
+            preview[0].name,
+            preview[0].id,
+          ])
+        );
+      } else {
+        exitStatus = EnigmailDialog.confirmDlg(
+          window,
           EnigmailLocale.getString("doImportMultiple", [
-            preview.map(function(a) {
-              return "\t" + a.name + " (" + a.id + ")";
-            }).join("\n")
-          ]));
+            preview
+              .map(function(a) {
+                return "\t" + a.name + " (" + a.id + ")";
+              })
+              .join("\n"),
+          ])
+        );
       }
 
       if (exitStatus) {
         try {
-          exitStatus = EnigmailKeyRing.importKey(window, false, keyData, "", errorMsgObj);
-        }
-        catch (ex) {}
+          exitStatus = EnigmailKeyRing.importKey(
+            window,
+            false,
+            keyData,
+            "",
+            errorMsgObj
+          );
+        } catch (ex) {}
 
         if (exitStatus === 0) {
           var keyList = preview.map(function(a) {
             return a.id;
           });
           EnigmailDialog.keyImportDlg(window, keyList);
-        }
-        else {
-          EnigmailDialog.alert(window, EnigmailLocale.getString("failKeyImport") + "\n" + errorMsgObj.value);
+        } else {
+          EnigmailDialog.alert(
+            window,
+            EnigmailLocale.getString("failKeyImport") + "\n" + errorMsgObj.value
+          );
         }
       }
-    }
-    else {
+    } else {
       EnigmailDialog.alert(window, EnigmailLocale.getString("noKeyFound"));
     }
   },
 
   /**
    * Extract the subject from the 1st content line and move it to the subject line
    */
-  movePEPsubject: function() {
+  movePEPsubject() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: movePEPsubject:\n");
 
     let bodyElement = this.getBodyElement();
 
-    if (bodyElement.textContent.search(/^\r?\n?Subject: [^\r\n]+\r?\n\r?\n/i) === 0 &&
-      ("subject" in currentHeaderData) &&
-      currentHeaderData.subject.headerValue === "pEp") {
-
+    if (
+      bodyElement.textContent.search(/^\r?\n?Subject: [^\r\n]+\r?\n\r?\n/i) ===
+        0 &&
+      "subject" in currentHeaderData &&
+      currentHeaderData.subject.headerValue === "pEp"
+    ) {
       if (gFolderDisplay.selectedMessage) {
         let m = EnigmailMime.extractSubjectFromBody(bodyElement.textContent);
         if (m) {
           let node = bodyElement.firstChild;
           let found = false;
 
-          while ((!found) && node) {
+          while (!found && node) {
             if (node.nodeName == "DIV") {
               node.innerHTML = EnigmailFuncs.formatPlaintextMsg(m.messageBody);
               found = true;
             }
             node = node.nextSibling;
           }
 
           // if no <DIV> node is found, try with <PRE> (bug 24762)
           node = bodyElement.firstChild;
-          while ((!found) && node) {
+          while (!found && node) {
             if (node.nodeName == "PRE") {
               node.innerHTML = EnigmailFuncs.formatPlaintextMsg(m.messageBody);
               found = true;
             }
             node = node.nextSibling;
           }
 
           Enigmail.hdrView.setSubject(m.subject);
@@ -1441,135 +1867,168 @@ Enigmail.msg = {
   },
 
   /**
    * Fix broken PGP/MIME messages from MS-Exchange by replacing the broken original
    * message with a fixed copy.
    *
    * no return
    */
-  fixBuggyExchangeMail: function() {
+  fixBuggyExchangeMail() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: fixBuggyExchangeMail:\n");
 
     function hideAndResetExchangePane() {
-      document.getElementById("enigmailBrokenExchangeBox").setAttribute("collapsed", "true");
-      document.getElementById("enigmailFixBrokenMessageProgress").setAttribute("collapsed", "true");
-      document.getElementById("enigmailFixBrokenMessageButton").removeAttribute("collapsed");
+      document
+        .getElementById("enigmailBrokenExchangeBox")
+        .setAttribute("collapsed", "true");
+      document
+        .getElementById("enigmailFixBrokenMessageProgress")
+        .setAttribute("collapsed", "true");
+      document
+        .getElementById("enigmailFixBrokenMessageButton")
+        .removeAttribute("collapsed");
     }
 
-    document.getElementById("enigmailFixBrokenMessageButton").setAttribute("collapsed", "true");
-    document.getElementById("enigmailFixBrokenMessageProgress").removeAttribute("collapsed");
+    document
+      .getElementById("enigmailFixBrokenMessageButton")
+      .setAttribute("collapsed", "true");
+    document
+      .getElementById("enigmailFixBrokenMessageProgress")
+      .removeAttribute("collapsed");
 
     let msg = gFolderDisplay.messageDisplay.displayedMessage;
 
     let p = EnigmailFixExchangeMsg.fixExchangeMessage(msg, this.buggyMailType);
-    p.then(
-      function _success(msgKey) {
-        // display message with given msgKey
-
-        EnigmailLog.DEBUG("enigmailMessengerOverlay.js: fixBuggyExchangeMail: _success: msgKey=" + msgKey + "\n");
-
-        if (msgKey) {
-          let index = gFolderDisplay.view.dbView.findIndexFromKey(msgKey, true);
-          EnigmailLog.DEBUG("  ** index = " + index + "\n");
-
-          EnigmailTimer.setTimeout(function() {
-            gFolderDisplay.view.dbView.selectMsgByKey(msgKey);
-          }, 750);
-        }
-
-        hideAndResetExchangePane();
+    p.then(function(msgKey) {
+      // display message with given msgKey
+
+      EnigmailLog.DEBUG(
+        "enigmailMessengerOverlay.js: fixBuggyExchangeMail: _success: msgKey=" +
+          msgKey +
+          "\n"
+      );
+
+      if (msgKey) {
+        let index = gFolderDisplay.view.dbView.findIndexFromKey(msgKey, true);
+        EnigmailLog.DEBUG("  ** index = " + index + "\n");
+
+        EnigmailTimer.setTimeout(function() {
+          gFolderDisplay.view.dbView.selectMsgByKey(msgKey);
+        }, 750);
       }
-    );
-    p.catch(function _rejected() {
-      EnigmailDialog.alert(window, EnigmailLocale.getString("fixBrokenExchangeMsg.failed"));
+
+      hideAndResetExchangePane();
+    });
+    p.catch(function() {
+      EnigmailDialog.alert(
+        window,
+        EnigmailLocale.getString("fixBrokenExchangeMsg.failed")
+      );
       hideAndResetExchangePane();
     });
   },
 
   /**
    * Hide attachments containing OpenPGP keys
    */
-  hidePgpKeys: function() {
+  hidePgpKeys() {
     let keys = [];
     for (let i = 0; i < currentAttachments.length; i++) {
-      if (currentAttachments[i].contentType.search(/^application\/pgp-keys/i) === 0) {
+      if (
+        currentAttachments[i].contentType.search(/^application\/pgp-keys/i) ===
+        0
+      ) {
         keys.push(i);
       }
     }
 
     if (keys.length > 0) {
       let attachmentList = document.getElementById("attachmentList");
 
       for (let i = keys.length; i > 0; i--) {
         currentAttachments.splice(keys[i - 1], 1);
       }
 
       if (attachmentList) {
         // delete all keys from attachment list
         while (attachmentList.firstChild) {
-          attachmentList.removeChild(attachmentList.firstChild);
+          attachmentList.firstChild.remove();
         }
 
         // build new attachment list
 
         /* global gBuildAttachmentsForCurrentMsg: true */
         let orig = gBuildAttachmentsForCurrentMsg;
         gBuildAttachmentsForCurrentMsg = false;
         displayAttachmentsForExpandedView();
         gBuildAttachmentsForCurrentMsg = orig;
       }
     }
-
   },
 
   /**
    * Attempt to work around bug with headers of MS-Exchange message.
    * Reload message content
    *
    * @return: true:  message displayed
    *          false: could not handle message
    */
-  displayBuggyExchangeMail: function() {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: displayBuggyExchangeMail\n");
-    let hdrs = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+  displayBuggyExchangeMail() {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: displayBuggyExchangeMail\n"
+    );
+    let hdrs = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+      Ci.nsIMimeHeaders
+    );
     hdrs.initialize(this.buggyExchangeEmailContent);
     let ct = hdrs.extractHeader("content-type", true);
 
     if (ct && ct.search(/^text\/plain/i) === 0) {
       let bi = this.buggyExchangeEmailContent.search(/\r?\n/);
       let boundary = this.buggyExchangeEmailContent.substr(2, bi - 2);
       let startMsg = this.buggyExchangeEmailContent.search(/\r?\n\r?\n/);
       let msgText;
 
       if (this.buggyMailType == "exchange") {
-        msgText = 'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="' + boundary + '"\r\n' +
+        msgText =
+          'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="' +
+          boundary +
+          '"\r\n' +
           this.buggyExchangeEmailContent.substr(startMsg);
-      }
-      else {
-        msgText = 'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="' + boundary + '"\r\n' +
-          "\r\n" + boundary + "\r\n" +
+      } else {
+        msgText =
+          'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="' +
+          boundary +
+          '"\r\n' +
+          "\r\n" +
+          boundary +
+          "\r\n" +
           "Content-Type: application/pgp-encrypted\r\n" +
           "Content-Description: PGP/MIME version identification\r\n\r\n" +
           "Version: 1\r\n\r\n" +
-          this.buggyExchangeEmailContent.substr(startMsg).replace(/^Content-Type: +application\/pgp-encrypted/im,
-            "Content-Type: application/octet-stream");
-
+          this.buggyExchangeEmailContent
+            .substr(startMsg)
+            .replace(
+              /^Content-Type: +application\/pgp-encrypted/im,
+              "Content-Type: application/octet-stream"
+            );
       }
 
       let enigmailSvc = Enigmail.getEnigmailSvc();
       if (!enigmailSvc) {
         return false;
       }
 
-      let uri = EnigmailURIs.createMessageURI(this.getCurrentMsgUrl(),
+      let uri = EnigmailURIs.createMessageURI(
+        this.getCurrentMsgUrl(),
         "message/rfc822",
         "",
         msgText,
-        false);
+        false
+      );
 
       EnigmailVerify.setMsgWindow(msgWindow, null);
       messenger.loadURL(window, uri);
 
       // Thunderbird
       let atv = document.getElementById("attachmentView");
       if (atv) {
         atv.setAttribute("collapsed", "true");
@@ -1577,71 +2036,79 @@ Enigmail.msg = {
 
       return true;
     }
 
     return false;
   },
 
   // check if the attachment could be encrypted
-  checkEncryptedAttach: function(attachment) {
-    return (EnigmailMsgRead.getAttachmentName(attachment).match(/\.(gpg|pgp|asc)$/i) ||
-      (attachment.contentType.match(/^application\/pgp(-.*)?$/i)) &&
-      (attachment.contentType.search(/^application\/pgp-signature/i) < 0));
+  checkEncryptedAttach(attachment) {
+    return (
+      EnigmailMsgRead.getAttachmentName(attachment).match(
+        /\.(gpg|pgp|asc)$/i
+      ) ||
+      (attachment.contentType.match(/^application\/pgp(-.*)?$/i) &&
+        attachment.contentType.search(/^application\/pgp-signature/i) < 0)
+    );
   },
 
-  getDecryptedMessage: function(contentType, includeHeaders) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: getDecryptedMessage: " + contentType + ", " + includeHeaders + "\n");
+  getDecryptedMessage(contentType, includeHeaders) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: getDecryptedMessage: " +
+        contentType +
+        ", " +
+        includeHeaders +
+        "\n"
+    );
 
     if (!Enigmail.msg.decryptedMessage) {
       return "No decrypted message found!\n";
     }
 
     var enigmailSvc = Enigmail.getEnigmailSvc();
     if (!enigmailSvc) {
       return "";
     }
 
     var headerList = Enigmail.msg.decryptedMessage.headerList;
-    var statusLine = Enigmail.msg.securityInfo ? Enigmail.msg.securityInfo.statusLine : "";
+    var statusLine = Enigmail.msg.securityInfo
+      ? Enigmail.msg.securityInfo.statusLine
+      : "";
     var contentData = "";
     var headerName;
 
     if (contentType == "message/rfc822") {
       // message/rfc822
 
       if (includeHeaders) {
         try {
-
           var msg = gFolderDisplay.selectedMessage;
           if (msg) {
             let msgHdr = {
-              "From": msg.author,
-              "Subject": msg.subject,
-              "To": msg.recipients,
-              "Cc": msg.ccList,
-              "Date": EnigmailTime.getDateTime(msg.dateInSeconds, true, true)
+              From: msg.author,
+              Subject: msg.subject,
+              To: msg.recipients,
+              Cc: msg.ccList,
+              Date: EnigmailTime.getDateTime(msg.dateInSeconds, true, true),
             };
 
-
             if (gFolderDisplay.selectedMessageIsNews) {
               if (currentHeaderData.newsgroups) {
                 msgHdr.Newsgroups = currentHeaderData.newsgroups.headerValue;
               }
             }
 
             for (let headerName in msgHdr) {
               if (msgHdr[headerName] && msgHdr[headerName].length > 0) {
                 contentData += headerName + ": " + msgHdr[headerName] + "\r\n";
               }
             }
-
           }
-        }
-        catch (ex) {
+        } catch (ex) {
           // the above seems to fail every now and then
           // so, here is the fallback
           for (let headerName in headerList) {
             let headerValue = headerList[headerName];
             contentData += headerName + ": " + headerValue + "\r\n";
           }
         }
 
@@ -1651,86 +2118,115 @@ Enigmail.msg = {
           contentData += "; charset=" + Enigmail.msg.decryptedMessage.charset;
         }
 
         contentData += "\r\n";
       }
 
       contentData += "\r\n";
 
-      if (Enigmail.msg.decryptedMessage.hasAttachments && (!Enigmail.msg.decryptedMessage.attachmentsEncrypted)) {
-        contentData += EnigmailData.convertFromUnicode(EnigmailLocale.getString("enigContentNote"), Enigmail.msg.decryptedMessage.charset);
+      if (
+        Enigmail.msg.decryptedMessage.hasAttachments &&
+        !Enigmail.msg.decryptedMessage.attachmentsEncrypted
+      ) {
+        contentData += EnigmailData.convertFromUnicode(
+          EnigmailLocale.getString("enigContentNote"),
+          Enigmail.msg.decryptedMessage.charset
+        );
       }
 
       contentData += Enigmail.msg.decryptedMessage.plainText;
-    }
-    else {
+    } else {
       // text/html or text/plain
 
       if (contentType == "text/html") {
-        contentData += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + Enigmail.msg.decryptedMessage.charset + "\">\r\n";
+        contentData +=
+          '<meta http-equiv="Content-Type" content="text/html; charset=' +
+          Enigmail.msg.decryptedMessage.charset +
+          '">\r\n';
         contentData += "<html><head></head><body>\r\n";
       }
 
       if (statusLine) {
         if (contentType == "text/html") {
-          contentData += "<b>" + EnigmailLocale.getString("enigHeader") + "</b> " +
-            EnigmailMsgRead.escapeTextForHTML(statusLine, false) + "<br>\r\n<hr>\r\n";
-        }
-        else {
-          contentData += EnigmailLocale.getString("enigHeader") + " " + statusLine + "\r\n\r\n";
+          contentData +=
+            "<b>" +
+            EnigmailLocale.getString("enigHeader") +
+            "</b> " +
+            EnigmailMsgRead.escapeTextForHTML(statusLine, false) +
+            "<br>\r\n<hr>\r\n";
+        } else {
+          contentData +=
+            EnigmailLocale.getString("enigHeader") +
+            " " +
+            statusLine +
+            "\r\n\r\n";
         }
       }
 
       if (includeHeaders) {
         for (headerName in headerList) {
           let headerValue = headerList[headerName];
 
           if (headerValue) {
             if (contentType == "text/html") {
-              contentData += "<b>" + EnigmailMsgRead.escapeTextForHTML(headerName, false) + ":</b> " +
-                EnigmailMsgRead.escapeTextForHTML(headerValue, false) + "<br>\r\n";
-            }
-            else {
+              contentData +=
+                "<b>" +
+                EnigmailMsgRead.escapeTextForHTML(headerName, false) +
+                ":</b> " +
+                EnigmailMsgRead.escapeTextForHTML(headerValue, false) +
+                "<br>\r\n";
+            } else {
               contentData += headerName + ": " + headerValue + "\r\n";
             }
           }
         }
       }
 
       if (contentType == "text/html") {
-        contentData += "<pre>" + EnigmailMsgRead.escapeTextForHTML(Enigmail.msg.decryptedMessage.plainText, false) + "</pre>\r\n";
+        contentData +=
+          "<pre>" +
+          EnigmailMsgRead.escapeTextForHTML(
+            Enigmail.msg.decryptedMessage.plainText,
+            false
+          ) +
+          "</pre>\r\n";
 
         contentData += "</body></html>\r\n";
-      }
-      else {
+      } else {
         contentData += "\r\n" + Enigmail.msg.decryptedMessage.plainText;
       }
 
-      if (!(EnigmailOS.isDosLike)) {
+      if (!EnigmailOS.isDosLike) {
         contentData = contentData.replace(/\r\n/g, "\n");
       }
     }
 
     return contentData;
   },
 
-
-  msgDefaultPrint: function(elementId) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: this.msgDefaultPrint: " + elementId + "\n");
-
-    goDoCommand(elementId.indexOf("printpreview") >= 0 ? "cmd_printpreview" : "cmd_print");
+  msgDefaultPrint(elementId) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: this.msgDefaultPrint: " + elementId + "\n"
+    );
+
+    goDoCommand(
+      elementId.includes("printpreview") ? "cmd_printpreview" : "cmd_print"
+    );
   },
 
-  msgPrint: function(elementId) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: msgPrint: " + elementId + "\n");
-
-    var contextMenu = (elementId.search("Context") > -1);
-
-    if (!Enigmail.msg.decryptedMessage || typeof(Enigmail.msg.decryptedMessage) == "undefined") {
+  msgPrint(elementId) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: msgPrint: " + elementId + "\n"
+    );
+
+    if (
+      !Enigmail.msg.decryptedMessage ||
+      typeof Enigmail.msg.decryptedMessage == "undefined"
+    ) {
       this.msgDefaultPrint(elementId);
       return;
     }
 
     var mailNewsUrl = this.getCurrentMsgUrl();
 
     if (!mailNewsUrl) {
       this.msgDefaultPrint(elementId);
@@ -1748,189 +2244,234 @@ Enigmail.msg = {
       this.msgDefaultPrint(elementId);
       return;
     }
 
     // Note: Trying to print text/html content does not seem to work with
     //       non-ASCII chars
     var msgContent = this.getDecryptedMessage("message/rfc822", true);
 
-    var uri = EnigmailURIs.createMessageURI(Enigmail.msg.decryptedMessage.url,
+    var uri = EnigmailURIs.createMessageURI(
+      Enigmail.msg.decryptedMessage.url,
       "message/rfc822",
       "",
       msgContent,
-      false);
+      false
+    );
     Enigmail.msg.createdURIs.push(uri);
 
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: msgPrint: uri=" + uri + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: msgPrint: uri=" + uri + "\n"
+    );
 
     var messageList = [uri];
-    var printPreview = (elementId.indexOf("printpreview") >= 0);
-
-    window.openDialog("chrome://messenger/content/msgPrintEngine.xhtml",
+    var printPreview = elementId.includes("printpreview");
+
+    window.openDialog(
+      "chrome://messenger/content/msgPrintEngine.xhtml",
       "",
       "chrome,dialog=no,all,centerscreen",
-      1, messageList, statusFeedback,
-      printPreview, Ci.nsIMsgPrintEngine.MNAB_PRINTPREVIEW_MSG,
-      window);
-
-    return;
+      1,
+      messageList,
+      statusFeedback,
+      printPreview,
+      Ci.nsIMsgPrintEngine.MNAB_PRINTPREVIEW_MSG,
+      window
+    );
   },
 
-  msgDirectDecrypt: function(interactive, importOnly, contentEncoding, charset, signature,
-    bufferSize, head, tail, msgUriSpec, callbackFunction, isAuto) {
-    EnigmailLog.WRITE("enigmailMessengerOverlay.js: msgDirectDecrypt: contentEncoding=" + contentEncoding + ", signature=" + signature + "\n");
+  msgDirectDecrypt(
+    interactive,
+    importOnly,
+    contentEncoding,
+    charset,
+    signature,
+    bufferSize,
+    head,
+    tail,
+    msgUriSpec,
+    callbackFunction,
+    isAuto
+  ) {
+    EnigmailLog.WRITE(
+      "enigmailMessengerOverlay.js: msgDirectDecrypt: contentEncoding=" +
+        contentEncoding +
+        ", signature=" +
+        signature +
+        "\n"
+    );
     var mailNewsUrl = this.getCurrentMsgUrl();
     if (!mailNewsUrl) {
       return;
     }
 
     var callbackArg = {
-      interactive: interactive,
-      importOnly: importOnly,
-      contentEncoding: contentEncoding,
-      charset: charset,
+      interactive,
+      importOnly,
+      contentEncoding,
+      charset,
       messageUrl: mailNewsUrl.spec,
-      msgUriSpec: msgUriSpec,
-      signature: signature,
+      msgUriSpec,
+      signature,
       data: "",
-      head: head,
-      tail: tail,
-      isAuto: isAuto,
-      callbackFunction: callbackFunction
+      head,
+      tail,
+      isAuto,
+      callbackFunction,
     };
 
     var msgSvc = messenger.messageServiceFromURI(msgUriSpec);
 
     var listener = {
       QueryInterface: EnigmailCompat.generateQI(["nsIStreamListener"]),
-      onStartRequest: function() {
+      onStartRequest() {
         this.data = "";
-        this.inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
-
+        this.inStream = Cc[
+          "@mozilla.org/scriptableinputstream;1"
+        ].createInstance(Ci.nsIScriptableInputStream);
       },
-      onStopRequest: function() {
+      onStopRequest() {
         var start = this.data.indexOf("-----BEGIN PGP");
         var end = this.data.indexOf("-----END PGP");
 
         if (start >= 0 && end > start) {
           var tStr = this.data.substr(end);
           var n = tStr.indexOf("\n");
           var r = tStr.indexOf("\r");
           var lEnd = -1;
           if (n >= 0 && r >= 0) {
             lEnd = Math.min(r, n);
-          }
-          else if (r >= 0) {
+          } else if (r >= 0) {
             lEnd = r;
-          }
-          else if (n >= 0) {
+          } else if (n >= 0) {
             lEnd = n;
           }
 
           if (lEnd >= 0) {
             end += lEnd;
           }
 
           callbackArg.data = this.data.substring(start, end + 1);
-          EnigmailLog.DEBUG("enigmailMessengerOverlay.js: data: >" + callbackArg.data.substr(0, 100) + "<\n");
+          EnigmailLog.DEBUG(
+            "enigmailMessengerOverlay.js: data: >" +
+              callbackArg.data.substr(0, 100) +
+              "<\n"
+          );
           Enigmail.msg.msgDirectCallback(callbackArg);
         }
-      }
+      },
     };
 
     listener.onDataAvailable = function(req, stream, offset, count) {
       this.inStream.init(stream);
       this.data += this.inStream.read(count);
     };
 
-    msgSvc.streamMessage(msgUriSpec,
+    msgSvc.streamMessage(
+      msgUriSpec,
       listener,
       msgWindow,
       null,
       false,
       null,
-      false);
-
+      false
+    );
   },
 
-
-  msgDirectCallback: function(callbackArg) {
+  msgDirectCallback(callbackArg) {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: msgDirectCallback: \n");
 
     var mailNewsUrl = Enigmail.msg.getCurrentMsgUrl();
     var urlSpec = mailNewsUrl ? mailNewsUrl.spec : "";
-    var newBufferSize = 0;
 
     var l = urlSpec.length;
 
     if (urlSpec.substr(0, l) != callbackArg.messageUrl.substr(0, l)) {
-      EnigmailLog.ERROR("enigmailMessengerOverlay.js: msgDirectCallback: Message URL mismatch " + mailNewsUrl.spec + " vs. " + callbackArg.messageUrl + "\n");
+      EnigmailLog.ERROR(
+        "enigmailMessengerOverlay.js: msgDirectCallback: Message URL mismatch " +
+          mailNewsUrl.spec +
+          " vs. " +
+          callbackArg.messageUrl +
+          "\n"
+      );
       return;
     }
 
     var msgText = callbackArg.data;
     msgText = EnigmailData.convertFromUnicode(msgText, "UTF-8");
 
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: msgDirectCallback: msgText='" + msgText.substr(0, 100) + "'\n");
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: msgDirectCallback: msgText='" +
+        msgText.substr(0, 100) +
+        "'\n"
+    );
 
     var f = function(argList) {
       var msgText = argList[0];
       var cb = argList[1];
-      cb.callbackFunction(msgText, cb.contentEncoding,
+      cb.callbackFunction(
+        msgText,
+        cb.contentEncoding,
         cb.charset,
         cb.interactive,
         cb.importOnly,
         cb.messageUrl,
         cb.signature,
         3,
         cb.head,
         cb.tail,
         cb.msgUriSpec,
-        cb.isAuto);
+        cb.isAuto
+      );
     };
 
     EnigmailEvents.dispatchEvent(f, 0, [msgText, callbackArg]);
   },
 
-
-  revealAttachments: function(index) {
+  revealAttachments(index) {
     if (!index) {
       index = 0;
     }
 
     if (index < currentAttachments.length) {
-      this.handleAttachment("revealName/" + index.toString(), currentAttachments[index]);
+      this.handleAttachment(
+        "revealName/" + index.toString(),
+        currentAttachments[index]
+      );
     }
   },
 
   // handle the attachment view toggle
-  handleAttchmentEvent: function() {
+  handleAttchmentEvent() {
     let attList = document.getElementById("attachmentList");
 
     let clickFunc = function(event) {
-      Enigmail.msg.attachmentListClick('attachmentList', event);
+      Enigmail.msg.attachmentListClick("attachmentList", event);
     };
 
     if (attList && attList.itemCount > 0) {
       for (let i = 0; i < attList.itemCount; i++) {
         let att = attList.getItemAtIndex(i);
         att.addEventListener("click", clickFunc, true);
       }
     }
   },
 
   // handle a selected attachment (decrypt & open or save)
-  handleAttachmentSel: function(actionType, selectedItem = null) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: handleAttachmentSel: actionType=" + actionType + "\n");
+  handleAttachmentSel(actionType, selectedItem = null) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: handleAttachmentSel: actionType=" +
+        actionType +
+        "\n"
+    );
 
     let selectedAttachments, anAttachment, contextMenu;
 
     // Thunderbird
-    contextMenu = document.getElementById('attachmentItemContext');
+    contextMenu = document.getElementById("attachmentItemContext");
 
     if (contextMenu) {
       // Thunderbird
       selectedAttachments = contextMenu.attachments;
       anAttachment = selectedAttachments[0];
     }
 
     switch (actionType) {
@@ -1944,432 +2485,545 @@ Enigmail.msg = {
         this.verifyDetachedSignature(anAttachment);
         break;
     }
   },
 
   /**
    * save the original file plus the signature file to disk and then verify the signature
    */
-  verifyDetachedSignature: function(anAttachment) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: verifyDetachedSignature: url=" + anAttachment.url + "\n");
+  verifyDetachedSignature(anAttachment) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: verifyDetachedSignature: url=" +
+        anAttachment.url +
+        "\n"
+    );
 
     var enigmailSvc = Enigmail.getEnigmailSvc();
     if (!enigmailSvc) {
       return;
     }
 
-    var origAtt,
-      signatureAtt;
+    var origAtt, signatureAtt;
     var isEncrypted = false;
 
-    if ((EnigmailMsgRead.getAttachmentName(anAttachment).search(/\.sig$/i) > 0) ||
-      (anAttachment.contentType.search(/^application\/pgp-signature/i) === 0)) {
+    if (
+      EnigmailMsgRead.getAttachmentName(anAttachment).search(/\.sig$/i) > 0 ||
+      anAttachment.contentType.search(/^application\/pgp-signature/i) === 0
+    ) {
       // we have the .sig file; need to know the original file;
 
       signatureAtt = anAttachment;
-      var origName = EnigmailMsgRead.getAttachmentName(anAttachment).replace(/\.sig$/i, "");
+      var origName = EnigmailMsgRead.getAttachmentName(anAttachment).replace(
+        /\.sig$/i,
+        ""
+      );
 
       for (let i = 0; i < currentAttachments.length; i++) {
-        if (origName == EnigmailMsgRead.getAttachmentName(currentAttachments[i])) {
+        if (
+          origName == EnigmailMsgRead.getAttachmentName(currentAttachments[i])
+        ) {
           origAtt = currentAttachments[i];
           break;
         }
       }
 
       if (!origAtt) {
         for (let i = 0; i < currentAttachments.length; i++) {
-          if (origName == EnigmailMsgRead.getAttachmentName(currentAttachments[i]).replace(/\.pgp$/i, "")) {
+          if (
+            origName ==
+            EnigmailMsgRead.getAttachmentName(currentAttachments[i]).replace(
+              /\.pgp$/i,
+              ""
+            )
+          ) {
             isEncrypted = true;
             origAtt = currentAttachments[i];
             break;
           }
         }
       }
-    }
-    else {
+    } else {
       // we have a supposedly original file; need to know the .sig file;
 
       origAtt = anAttachment;
       var attachName = EnigmailMsgRead.getAttachmentName(anAttachment);
       var sigName = attachName + ".sig";
 
       for (let i = 0; i < currentAttachments.length; i++) {
-        if (sigName == EnigmailMsgRead.getAttachmentName(currentAttachments[i])) {
+        if (
+          sigName == EnigmailMsgRead.getAttachmentName(currentAttachments[i])
+        ) {
           signatureAtt = currentAttachments[i];
           break;
         }
       }
 
       if (!signatureAtt && attachName.search(/\.pgp$/i) > 0) {
-        sigName = attachName.replace(/\.pgp$/i, '.sig');
+        sigName = attachName.replace(/\.pgp$/i, ".sig");
         for (let i = 0; i < currentAttachments.length; i++) {
-          if (sigName == EnigmailMsgRead.getAttachmentName(currentAttachments[i])) {
+          if (
+            sigName == EnigmailMsgRead.getAttachmentName(currentAttachments[i])
+          ) {
             isEncrypted = true;
             signatureAtt = currentAttachments[i];
             break;
           }
         }
       }
     }
 
     if (!signatureAtt) {
-      EnigmailDialog.alert(window, EnigmailLocale.getString("attachment.noMatchToSignature", [EnigmailMsgRead.getAttachmentName(origAtt)]));
+      EnigmailDialog.alert(
+        window,
+        EnigmailLocale.getString("attachment.noMatchToSignature", [
+          EnigmailMsgRead.getAttachmentName(origAtt),
+        ])
+      );
       return;
     }
     if (!origAtt) {
-      EnigmailDialog.alert(window, EnigmailLocale.getString("attachment.noMatchFromSignature", [EnigmailMsgRead.getAttachmentName(signatureAtt)]));
+      EnigmailDialog.alert(
+        window,
+        EnigmailLocale.getString("attachment.noMatchFromSignature", [
+          EnigmailMsgRead.getAttachmentName(signatureAtt),
+        ])
+      );
       return;
     }
 
     // open
     var tmpDir = EnigmailFiles.getTempDir();
-    var outFile1,
-      outFile2;
+    var outFile1, outFile2;
     outFile1 = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
     outFile1.initWithPath(tmpDir);
     if (!(outFile1.isDirectory() && outFile1.isWritable())) {
       EnigmailDialog.alert(window, EnigmailLocale.getString("noTempDir"));
       return;
     }
     outFile1.append(EnigmailMsgRead.getAttachmentName(origAtt));
     outFile1.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
     EnigmailFiles.writeUrlToFile(origAtt.url, outFile1);
 
     if (isEncrypted) {
       // Try to decrypt message if we suspect the message is encrypted. If it fails we will just verify the encrypted data.
-      EnigmailDecryption.decryptAttachment(window, outFile1,
+      EnigmailDecryption.decryptAttachment(
+        window,
+        outFile1,
         EnigmailMsgRead.getAttachmentName(origAtt),
-        EnigmailFiles.readBinaryFile(outFile1), {}, {}, {});
+        EnigmailFiles.readBinaryFile(outFile1),
+        {},
+        {},
+        {}
+      );
     }
 
     outFile2 = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
     outFile2.initWithPath(tmpDir);
     outFile2.append(EnigmailMsgRead.getAttachmentName(signatureAtt));
     outFile2.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
     EnigmailFiles.writeUrlToFile(signatureAtt.url, outFile2);
 
     var promise = EnigmailVerifyAttachment.attachment(outFile1, outFile2);
     promise.then(function(message) {
-      EnigmailDialog.info(window, EnigmailLocale.getString("signature.verifiedOK", [EnigmailMsgRead.getAttachmentName(origAtt)]) + "\n\n" + message);
+      EnigmailDialog.info(
+        window,
+        EnigmailLocale.getString("signature.verifiedOK", [
+          EnigmailMsgRead.getAttachmentName(origAtt),
+        ]) +
+          "\n\n" +
+          message
+      );
     });
     promise.catch(function(err) {
-      EnigmailDialog.alert(window, EnigmailLocale.getString("signature.verifyFailed", [EnigmailMsgRead.getAttachmentName(origAtt)]) + "\n\n" +
-        err);
+      EnigmailDialog.alert(
+        window,
+        EnigmailLocale.getString("signature.verifyFailed", [
+          EnigmailMsgRead.getAttachmentName(origAtt),
+        ]) +
+          "\n\n" +
+          err
+      );
     });
 
     outFile1.remove(false);
     outFile2.remove(false);
   },
 
-  handleAttachment: function(actionType, anAttachment) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: handleAttachment: actionType=" + actionType + ", anAttachment(url)=" + anAttachment.url + "\n");
+  handleAttachment(actionType, anAttachment) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: handleAttachment: actionType=" +
+        actionType +
+        ", anAttachment(url)=" +
+        anAttachment.url +
+        "\n"
+    );
 
     var argumentsObj = {
-      actionType: actionType,
+      actionType,
       attachment: anAttachment,
       forceBrowser: false,
-      data: ""
+      data: "",
     };
 
-    var f = function _cb(data) {
+    var f = function(data) {
       argumentsObj.data = data;
       Enigmail.msg.decryptAttachmentCallback([argumentsObj]);
     };
 
     var bufferListener = EnigmailStreams.newStringStreamListener(f);
-    var ioServ = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
-    var msgUri = ioServ.newURI(argumentsObj.attachment.url, null, null);
+    var ioServ = Services.io;
+    var msgUri = ioServ.newURI(argumentsObj.attachment.url);
 
     var channel = EnigmailStreams.createChannel(msgUri);
     channel.asyncOpen(bufferListener, msgUri);
   },
 
-  setAttachmentName: function(attachment, newLabel, index) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: setAttachmentName (" + newLabel + "):\n");
+  setAttachmentName(attachment, newLabel, index) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: setAttachmentName (" + newLabel + "):\n"
+    );
 
     var attList = document.getElementById("attachmentList");
     if (attList) {
       var attNode = attList.firstChild;
       while (attNode) {
         if (attNode.getAttribute("name") == attachment.name) {
           attNode.setAttribute("name", newLabel);
         }
         attNode = attNode.nextSibling;
       }
     }
 
-    if (typeof(attachment.displayName) == "undefined") {
+    if (typeof attachment.displayName == "undefined") {
       attachment.name = newLabel;
-    }
-    else {
+    } else {
       attachment.displayName = newLabel;
     }
 
     if (index && index.length > 0) {
       this.revealAttachments(parseInt(index, 10) + 1);
     }
   },
 
-  decryptAttachmentCallback: function(cbArray) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: decryptAttachmentCallback:\n");
+  decryptAttachmentCallback(cbArray) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: decryptAttachmentCallback:\n"
+    );
 
     var callbackArg = cbArray[0];
 
     var exitCodeObj = {};
     var statusFlagsObj = {};
     var errorMsgObj = {};
     var exitStatus = -1;
 
-    var enigmailSvc = Enigmail.getEnigmailSvc();
     var outFile;
     var origFilename;
-    var rawFileName = EnigmailMsgRead.getAttachmentName(callbackArg.attachment).replace(/\.(asc|pgp|gpg)$/i, "");
+    var rawFileName = EnigmailMsgRead.getAttachmentName(
+      callbackArg.attachment
+    ).replace(/\.(asc|pgp|gpg)$/i, "");
 
     if (callbackArg.actionType != "importKey") {
       origFilename = EnigmailAttachment.getFileName(window, callbackArg.data);
       if (origFilename && origFilename.length > rawFileName.length) {
         rawFileName = origFilename;
       }
     }
 
     if (callbackArg.actionType == "saveAttachment") {
-      outFile = EnigmailDialog.filePicker(window, EnigmailLocale.getString("saveAttachmentHeader"),
-        Enigmail.msg.lastSaveDir, true, "",
-        rawFileName, null);
+      outFile = EnigmailDialog.filePicker(
+        window,
+        EnigmailLocale.getString("saveAttachmentHeader"),
+        Enigmail.msg.lastSaveDir,
+        true,
+        "",
+        rawFileName,
+        null
+      );
       if (!outFile) {
         return;
       }
-    }
-    else if (callbackArg.actionType.substr(0, 10) == "revealName") {
+    } else if (callbackArg.actionType.substr(0, 10) == "revealName") {
       if (origFilename && origFilename.length > 0) {
-        Enigmail.msg.setAttachmentName(callbackArg.attachment, origFilename + ".pgp", callbackArg.actionType.substr(11, 10));
+        Enigmail.msg.setAttachmentName(
+          callbackArg.attachment,
+          origFilename + ".pgp",
+          callbackArg.actionType.substr(11, 10)
+        );
       }
       Enigmail.msg.setAttachmentReveal(null);
       return;
-    }
-    else {
+    } else {
       // open
       var tmpDir = EnigmailFiles.getTempDir();
       try {
         outFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
         outFile.initWithPath(tmpDir);
         if (!(outFile.isDirectory() && outFile.isWritable())) {
           errorMsgObj.value = EnigmailLocale.getString("noTempDir");
           return;
         }
         outFile.append(rawFileName);
         outFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
-      }
-      catch (ex) {
+      } catch (ex) {
         errorMsgObj.value = EnigmailLocale.getString("noTempDir");
         return;
       }
     }
 
     if (callbackArg.actionType == "importKey") {
-      var preview = EnigmailKey.getKeyListFromKeyBlock(callbackArg.data, errorMsgObj);
+      var preview = EnigmailKey.getKeyListFromKeyBlock(
+        callbackArg.data,
+        errorMsgObj
+      );
 
       if (errorMsgObj.value !== "" || preview.length === 0) {
         // try decrypting the attachment
-        exitStatus = EnigmailDecryption.decryptAttachment(window, outFile,
+        exitStatus = EnigmailDecryption.decryptAttachment(
+          window,
+          outFile,
           EnigmailMsgRead.getAttachmentName(callbackArg.attachment),
           callbackArg.data,
-          exitCodeObj, statusFlagsObj,
-          errorMsgObj);
-        if ((exitStatus) && exitCodeObj.value === 0) {
+          exitCodeObj,
+          statusFlagsObj,
+          errorMsgObj
+        );
+        if (exitStatus && exitCodeObj.value === 0) {
           // success decrypting, let's try again
           callbackArg.data = EnigmailFiles.readBinaryFile(outFile);
-          preview = EnigmailKey.getKeyListFromKeyBlock(callbackArg.data, errorMsgObj);
+          preview = EnigmailKey.getKeyListFromKeyBlock(
+            callbackArg.data,
+            errorMsgObj
+          );
         }
       }
 
       if (errorMsgObj.value === "") {
         this.importKeyDataWithConfirmation(preview, callbackArg.data);
-      }
-      else {
-        EnigmailDialog.alert(window, EnigmailLocale.getString("previewFailed") + "\n" + errorMsgObj.value);
+      } else {
+        EnigmailDialog.alert(
+          window,
+          EnigmailLocale.getString("previewFailed") + "\n" + errorMsgObj.value
+        );
       }
       outFile.remove(true);
       return;
     }
 
-    exitStatus = EnigmailDecryption.decryptAttachment(window, outFile,
+    exitStatus = EnigmailDecryption.decryptAttachment(
+      window,
+      outFile,
       EnigmailMsgRead.getAttachmentName(callbackArg.attachment),
       callbackArg.data,
-      exitCodeObj, statusFlagsObj,
-      errorMsgObj);
-
-    if ((!exitStatus) || exitCodeObj.value !== 0) {
+      exitCodeObj,
+      statusFlagsObj,
+      errorMsgObj
+    );
+
+    if (!exitStatus || exitCodeObj.value !== 0) {
       exitStatus = false;
-      if ((statusFlagsObj.value & EnigmailConstants.DECRYPTION_OKAY) &&
-        (statusFlagsObj.value & EnigmailConstants.UNVERIFIED_SIGNATURE)) {
-
+      if (
+        statusFlagsObj.value & EnigmailConstants.DECRYPTION_OKAY &&
+        statusFlagsObj.value & EnigmailConstants.UNVERIFIED_SIGNATURE
+      ) {
         if (callbackArg.actionType == "openAttachment") {
-          exitStatus = EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("decryptOkNoSig"), EnigmailLocale.getString("msgOvl.button.contAnyway"));
+          exitStatus = EnigmailDialog.confirmDlg(
+            window,
+            EnigmailLocale.getString("decryptOkNoSig"),
+            EnigmailLocale.getString("msgOvl.button.contAnyway")
+          );
+        } else {
+          EnigmailDialog.info(
+            window,
+            EnigmailLocale.getString("decryptOkNoSig")
+          );
         }
-        else {
-          EnigmailDialog.info(window, EnigmailLocale.getString("decryptOkNoSig"));
-        }
-      }
-      else {
-        EnigmailDialog.info(window, EnigmailLocale.getString("failedDecrypt") + "\n\n" + errorMsgObj.value);
+      } else {
+        EnigmailDialog.info(
+          window,
+          EnigmailLocale.getString("failedDecrypt") + "\n\n" + errorMsgObj.value
+        );
         exitStatus = false;
       }
     }
     if (exitStatus) {
       if (statusFlagsObj.value & EnigmailConstants.IMPORTED_KEY) {
-
         if (exitCodeObj.keyList) {
           let importKeyList = exitCodeObj.keyList.map(function(a) {
             return a.id;
           });
           EnigmailDialog.keyImportDlg(window, importKeyList);
         }
-      }
-      else if (statusFlagsObj.value & EnigmailConstants.DISPLAY_MESSAGE) {
-        HandleSelectedAttachments('open');
-      }
-      else if ((statusFlagsObj.value & EnigmailConstants.DISPLAY_MESSAGE) ||
-        (callbackArg.actionType == "openAttachment")) {
-        var ioServ = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
+      } else if (statusFlagsObj.value & EnigmailConstants.DISPLAY_MESSAGE) {
+        HandleSelectedAttachments("open");
+      } else if (
+        statusFlagsObj.value & EnigmailConstants.DISPLAY_MESSAGE ||
+        callbackArg.actionType == "openAttachment"
+      ) {
+        var ioServ = Services.io;
         var outFileUri = ioServ.newFileURI(outFile);
         var fileExt = outFile.leafName.replace(/(.*\.)(\w+)$/, "$2");
         if (fileExt && !callbackArg.forceBrowser) {
-          var extAppLauncher = Cc["@mozilla.org/mime;1"].getService(Ci.nsPIExternalAppLauncher);
+          var extAppLauncher = Cc["@mozilla.org/mime;1"].getService(
+            Ci.nsPIExternalAppLauncher
+          );
           extAppLauncher.deleteTemporaryFileOnExit(outFile);
 
           try {
-            var mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
+            var mimeService = Cc["@mozilla.org/mime;1"].getService(
+              Ci.nsIMIMEService
+            );
             var fileMimeType = mimeService.getTypeFromFile(outFile);
-            var fileMimeInfo = mimeService.getFromTypeAndExtension(fileMimeType, fileExt);
+            var fileMimeInfo = mimeService.getFromTypeAndExtension(
+              fileMimeType,
+              fileExt
+            );
 
             fileMimeInfo.launchWithFile(outFile);
-          }
-          catch (ex) {
+          } catch (ex) {
             // if the attachment file type is unknown, an exception is thrown,
             // so let it be handled by a browser window
             Enigmail.msg.loadExternalURL(outFileUri.asciiSpec);
           }
-        }
-        else {
+        } else {
           // open the attachment using an external application
           Enigmail.msg.loadExternalURL(outFileUri.asciiSpec);
         }
       }
     }
   },
 
-  loadExternalURL: function(url) {
+  loadExternalURL(url) {
     messenger.launchExternalURL(url);
   },
 
   // retrieves the most recent navigator window (opens one if need be)
-  loadURLInNavigatorWindow: function(url, aOpenFlag) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: loadURLInNavigatorWindow: " + url + ", " + aOpenFlag + "\n");
+  loadURLInNavigatorWindow(url, aOpenFlag) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: loadURLInNavigatorWindow: " +
+        url +
+        ", " +
+        aOpenFlag +
+        "\n"
+    );
 
     var navWindow;
 
     // if this is a browser window, just use it
     if ("document" in top) {
       var possibleNavigator = top.document.getElementById("main-window");
-      if (possibleNavigator &&
-        possibleNavigator.getAttribute("windowtype") == "navigator:browser") {
+      if (
+        possibleNavigator &&
+        possibleNavigator.getAttribute("windowtype") == "navigator:browser"
+      ) {
         navWindow = top;
       }
     }
 
     // if not, get the most recently used browser window
     if (!navWindow) {
-      var wm;
-      wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(
-        Ci.nsIWindowMediator);
+      var wm = Services.wm;
       navWindow = wm.getMostRecentWindow("navigator:browser");
     }
 
     if (navWindow) {
-
       if ("loadURI" in navWindow) {
         navWindow.loadURI(url);
-      }
-      else {
+      } else {
         navWindow._content.location.href = url;
       }
-
-    }
-    else if (aOpenFlag) {
+    } else if (aOpenFlag) {
       // if no browser window available and it's ok to open a new one, do so
       navWindow = window.open(url, "Enigmail");
     }
 
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: loadURLInNavigatorWindow: navWindow=" + navWindow + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: loadURLInNavigatorWindow: navWindow=" +
+        navWindow +
+        "\n"
+    );
 
     return navWindow;
   },
 
   // handle double click events on Attachments
-  attachmentListClick: function(elementId, event) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: attachmentListClick: event=" + event + "\n");
+  attachmentListClick(elementId, event) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: attachmentListClick: event=" + event + "\n"
+    );
 
     var attachment = event.target.attachment;
     if (this.checkEncryptedAttach(attachment)) {
-      if (event.button === 0 && event.detail == 2) { // double click
+      if (event.button === 0 && event.detail == 2) {
+        // double click
         this.handleAttachment("openAttachment", attachment);
         event.stopPropagation();
       }
     }
   },
 
   // create a decrypted copy of all selected messages in a target folder
 
-  decryptToFolder: function(destFolder) {
+  decryptToFolder(destFolder) {
     let msgHdrs = gFolderDisplay ? gFolderDisplay.selectedMessages : null;
     if (!msgHdrs || msgHdrs.length === 0) {
       return;
     }
 
-    EnigmailPersistentCrypto.dispatchMessages(msgHdrs, destFolder.URI, false, false);
+    EnigmailPersistentCrypto.dispatchMessages(
+      msgHdrs,
+      destFolder.URI,
+      false,
+      false
+    );
   },
 
-  importAttachedKeys: function() {
+  importAttachedKeys() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: importAttachedKeys\n");
 
     let keyFound = false;
 
     for (let i in currentAttachments) {
-      if (currentAttachments[i].contentType.search(/application\/pgp-keys/i) >= 0 ||
-        EnigmailMsgRead.getAttachmentName(currentAttachments[i]).match(/\.asc\.(gpg|pgp)$/i)) {
+      if (
+        currentAttachments[i].contentType.search(/application\/pgp-keys/i) >=
+          0 ||
+        EnigmailMsgRead.getAttachmentName(currentAttachments[i]).match(
+          /\.asc\.(gpg|pgp)$/i
+        )
+      ) {
         // found attached key
         this.handleAttachment("importKey", currentAttachments[i]);
         keyFound = true;
       }
     }
 
     return keyFound;
   },
 
-  importKeyFromKeyserver: function() {
+  importKeyFromKeyserver() {
     var pubKeyId = "0x" + Enigmail.msg.securityInfo.keyId;
     var inputObj = {
       searchList: [pubKeyId],
-      autoKeyServer: EnigmailPrefs.getPref("autoKeyServerSelection") ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0] : null
+      autoKeyServer: EnigmailPrefs.getPref("autoKeyServerSelection")
+        ? EnigmailPrefs.getPref("keyserver").split(/[ ,;]/g)[0]
+        : null,
     };
     var resultObj = {};
     EnigmailWindows.downloadKeys(window, inputObj, resultObj);
 
-
     if (resultObj.importedKeys > 0) {
       return true;
     }
 
     return false;
   },
 
   // download or import keys
-  handleUnknownKey: function() {
+  handleUnknownKey() {
     let imported = false;
     // handline keys embedded in message body
 
     if (Enigmail.msg.securityInfo.statusFlags & EnigmailConstants.INLINE_KEY) {
       //return Enigmail.msg.messageDecrypt(true, false);
       return Enigmail.msg.messageImport();
     }
 
@@ -2384,18 +3038,20 @@ Enigmail.msg = {
 
     return null;
   },
 
   /**
    * Create an artificial Autocrypt: header if there was no such header on the message
    * and the message was signed
    */
-  createArtificialAutocryptHeader: function() {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: createArtificialAutocryptHeader\n");
+  createArtificialAutocryptHeader() {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: createArtificialAutocryptHeader\n"
+    );
 
     if ("autocrypt" in currentHeaderData) {
       return;
     }
 
     let created = false;
     let dateValue = "",
       fromValue = "";
@@ -2407,89 +3063,115 @@ Enigmail.msg = {
       fromValue = currentHeaderData.from.headerValue;
     }
 
     if (Enigmail.msg.securityInfo && Enigmail.msg.securityInfo.statusFlags) {
       let securityInfo = Enigmail.msg.securityInfo;
       let keyObj = EnigmailKeyRing.getKeyById(securityInfo.keyId);
       if (keyObj && keyObj.getEncryptionValidity().keyValid) {
         if (securityInfo.statusFlags & EnigmailConstants.GOOD_SIGNATURE) {
-          let hdrData = "addr=" + EnigmailFuncs.stripEmail(fromValue) +
-            ((securityInfo.statusFlags & EnigmailConstants.DECRYPTION_OKAY) ||
-              (securityInfo.statusFlags & EnigmailConstants.PGP_MIME_ENCRYPTED) ? "; prefer-encrypt=mutual" : "") +
-            "; _enigmail_artificial=yes; _enigmail_fpr=" + keyObj.fpr + '; keydata="LQ=="';
+          let hdrData =
+            "addr=" +
+            EnigmailFuncs.stripEmail(fromValue) +
+            (securityInfo.statusFlags & EnigmailConstants.DECRYPTION_OKAY ||
+            securityInfo.statusFlags & EnigmailConstants.PGP_MIME_ENCRYPTED
+              ? "; prefer-encrypt=mutual"
+              : "") +
+            "; _enigmail_artificial=yes; _enigmail_fpr=" +
+            keyObj.fpr +
+            '; keydata="LQ=="';
 
           created = true;
 
-          EnigmailAutocrypt.processAutocryptHeader(fromValue, [hdrData], dateValue,
-            Enigmail.msg.isAutocryptEnabled());
+          EnigmailAutocrypt.processAutocryptHeader(
+            fromValue,
+            [hdrData],
+            dateValue,
+            Enigmail.msg.isAutocryptEnabled()
+          );
         }
       }
     }
 
     if (!created) {
-      let hdrData = "addr=" + EnigmailFuncs.stripEmail(fromValue) +
+      let hdrData =
+        "addr=" +
+        EnigmailFuncs.stripEmail(fromValue) +
         '; prefer-encrypt=reset; _enigmail_artificial=yes; keydata="LQ=="';
 
-      EnigmailAutocrypt.processAutocryptHeader(fromValue, [hdrData], dateValue,
-        Enigmail.msg.isAutocryptEnabled());
+      EnigmailAutocrypt.processAutocryptHeader(
+        fromValue,
+        [hdrData],
+        dateValue,
+        Enigmail.msg.isAutocryptEnabled()
+      );
     }
   },
 
-  flexActionRequest: function() {
+  flexActionRequest() {
     switch (Enigmail.msg.securityInfo.xtraStatus) {
       case "wks-request":
         this.confirmWksRequest();
         break;
       case "autocrypt-setup":
         this.performAutocryptSetup();
         break;
       case "process-manually":
         this.messageDecrypt(null, false);
         break;
     }
   },
 
-  confirmWksRequest: function() {
+  confirmWksRequest() {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: confirmWksRequest()\n");
     try {
       var msg = gFolderDisplay.selectedMessage;
       if (!(!msg || !msg.folder)) {
-        var accMgr = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
         var msgHdr = msg.folder.GetMessageHeader(msg.messageKey);
         let email = EnigmailFuncs.stripEmail(msgHdr.recipients);
         let maybeIdent = EnigmailStdlib.getIdentityForEmail(email);
 
         if (maybeIdent && maybeIdent.identity) {
           EnigmailStdlib.msgHdrsModifyRaw([msgHdr], function(data) {
-            EnigmailWks.confirmKey(maybeIdent.identity, data, window, function(ret) {
+            EnigmailWks.confirmKey(maybeIdent.identity, data, window, function(
+              ret
+            ) {
               if (ret) {
-                EnigmailDialog.info(window, EnigmailLocale.getString("wksConfirmSuccess"));
-              }
-              else {
-                EnigmailDialog.alert(window, EnigmailLocale.getString("wksConfirmFailure"));
+                EnigmailDialog.info(
+                  window,
+                  EnigmailLocale.getString("wksConfirmSuccess")
+                );
+              } else {
+                EnigmailDialog.alert(
+                  window,
+                  EnigmailLocale.getString("wksConfirmFailure")
+                );
               }
             });
             return null;
           });
-        }
-        else {
-          EnigmailDialog.alert(window, EnigmailLocale.getString("wksNoIdentity", [email]));
+        } else {
+          EnigmailDialog.alert(
+            window,
+            EnigmailLocale.getString("wksNoIdentity", [email])
+          );
         }
       }
-    }
-    catch (e) {
+    } catch (e) {
       EnigmailLog.DEBUG(e + "\n");
     }
   },
 
-  performAutocryptSetup: function(passwd = null) {
+  performAutocryptSetup(passwd = null) {
     EnigmailLog.DEBUG("enigmailMessengerOverlay.js: performAutocryptSetup()\n");
-    
-    EnigmailDialog.alert(window, "EnigmailAutocrypt.handleBackupMessage not implemented");
+
+    EnigmailDialog.alert(
+      window,
+      "EnigmailAutocrypt.handleBackupMessage not implemented"
+    );
 
     /*
     if (("message-id" in currentHeaderData) && EnigmailAutocrypt.isSelfCreatedSetupMessage(currentHeaderData["message-id"].headerValue)) {
       EnigmailDialog.info(window, EnigmailLocale.getString("autocrypt.importSetupKey.selfCreated"));
       return;
     }
 
     if (EnigmailAutocrypt.isAccountSetupForPgp(currentHeaderData.from.headerValue)) {
@@ -2533,27 +3215,34 @@ Enigmail.msg = {
             EnigmailDialog.alert(window, EnigmailLocale.getString("autocrypt.importSetupKey.invalidKey"));
             break;
         }
       });
     }
     */
   },
 
-  onUnloadEnigmail: function() {
+  onUnloadEnigmail() {
     //EnigmailLog.DEBUG("enigmailMessengerOverlay.js: onUnloadEnigmail()\n");
 
-    window.removeEventListener("unload", Enigmail.msg.messengerClose, false);
-    window.removeEventListener("unload-enigmail", Enigmail.msg.onUnloadEnigmail, false);
-    window.removeEventListener("load-enigmail", Enigmail.msg.messengerStartup, false);
+    window.removeEventListener("unload", Enigmail.msg.messengerClose);
+    window.removeEventListener(
+      "unload-enigmail",
+      Enigmail.msg.onUnloadEnigmail
+    );
+    window.removeEventListener("load-enigmail", Enigmail.msg.messengerStartup);
 
     this.messageCleanup();
 
     if (this.messagePane) {
-      this.messagePane.removeEventListener("unload", Enigmail.msg.messageFrameUnload, true);
+      this.messagePane.removeEventListener(
+        "unload",
+        Enigmail.msg.messageFrameUnload,
+        true
+      );
     }
 
     for (let c of this.changedAttributes) {
       let elem = document.getElementById(c.id);
       if (elem) {
         elem.setAttribute(c.attrib, c.value);
       }
     }
@@ -2573,14 +3262,23 @@ Enigmail.msg = {
     if (Enigmail.columnHandler) {
       Enigmail.columnHandler.onUnloadEnigmail();
     }
     if (Enigmail.hdrView) {
       Enigmail.hdrView.onUnloadEnigmail();
     }
 
     Enigmail = undefined;
-  }
+  },
 };
 
-window.addEventListener("load-enigmail", Enigmail.msg.messengerStartup.bind(Enigmail.msg), false);
-window.addEventListener("unload", Enigmail.msg.messengerClose.bind(Enigmail.msg), false);
-window.addEventListener("unload-enigmail", Enigmail.msg.onUnloadEnigmail.bind(Enigmail.msg), false);
+window.addEventListener(
+  "load-enigmail",
+  Enigmail.msg.messengerStartup.bind(Enigmail.msg)
+);
+window.addEventListener(
+  "unload",
+  Enigmail.msg.messengerClose.bind(Enigmail.msg)
+);
+window.addEventListener(
+  "unload-enigmail",
+  Enigmail.msg.onUnloadEnigmail.bind(Enigmail.msg)
+);
--- a/mail/extensions/openpgp/content/ui/enigmailMsgBox.js
+++ b/mail/extensions/openpgp/content/ui/enigmailMsgBox.js
@@ -1,24 +1,27 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-var EnigmailClipboard = ChromeUtils.import("chrome://openpgp/content/modules/clipboard.jsm").EnigmailClipboard;
-var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailEvents = ChromeUtils.import("chrome://openpgp/content/modules/events.jsm").EnigmailEvents;
+var EnigmailClipboard = ChromeUtils.import(
+  "chrome://openpgp/content/modules/clipboard.jsm"
+).EnigmailClipboard;
+var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailEvents = ChromeUtils.import(
+  "chrome://openpgp/content/modules/events.jsm"
+).EnigmailEvents;
 
 function onLoad() {
   var dlg = document.getElementById("enigmailMsgBox");
   dlg.getButton("help").setAttribute("hidden", "true");
   dlg.getButton("cancel").setAttribute("hidden", "true");
   dlg.getButton("extra1").setAttribute("hidden", "true");
   dlg.getButton("extra2").setAttribute("hidden", "true");
 
@@ -27,17 +30,16 @@ function onLoad() {
 
   let args = window.arguments[0];
   let msgtext = args.msgtext;
   let button1 = args.button1;
   let button2 = args.button2;
   let button3 = args.button3;
   let buttonCancel = args.cancelButton;
   let checkboxLabel = args.checkboxLabel;
-  let iconType = args.iconType;
 
   if (args.iconType) {
     let icn = document.getElementById("infoImage");
     icn.removeAttribute("collapsed");
     let iconClass = "";
 
     switch (args.iconType) {
       case 2:
@@ -99,24 +101,28 @@ function resizeDlg() {
   if (window.outerHeight > availHeight - 100) {
     let box = document.getElementById("msgContainer");
     let dlg = document.getElementById("enigmailMsgBox");
     let btnHeight = dlg.getButton("accept").parentNode.clientHeight + 20;
     let boxHeight = box.clientHeight;
     let dlgHeight = dlg.clientHeight;
 
     box.setAttribute("style", "overflow: auto;");
-    box.setAttribute("height", boxHeight - btnHeight - (dlgHeight - availHeight));
+    box.setAttribute(
+      "height",
+      boxHeight - btnHeight - (dlgHeight - availHeight)
+    );
     window.outerHeight = availHeight;
   }
 }
 
 function centerDialog() {
-  if (!EnigmailOS.isMac)
+  if (!EnigmailOS.isMac) {
     document.getElementById("enigmailMsgBox").centerWindowOnScreen();
+  }
 }
 
 function setButton(buttonId, label) {
   var labelType = buttonId;
 
   var dlg = document.getElementById("enigmailMsgBox");
   var elem = dlg.getButton(labelType);
 
@@ -158,33 +164,33 @@ function dlgClose(buttonId) {
     case "extra2":
       buttonNumber = 2;
       break;
     case "cancel":
       buttonNumber = -1;
   }
 
   window.arguments[1].value = buttonNumber;
-  window.arguments[1].checked = (document.getElementById("theCheckBox").getAttribute("checked") == "true");
+  window.arguments[1].checked =
+    document.getElementById("theCheckBox").getAttribute("checked") == "true";
   window.close();
 }
 
 function checkboxCb() {
   // do nothing
 }
 
-
 function copyToClipbrd() {
   let s = window.getSelection().toString();
 
   EnigmailClipboard.setClipboardContent(s);
 }
 
 function onKeyPress(event) {
   if (event.key == "c" && event.getModifierState("Accel")) {
     copyToClipbrd();
     event.stopPropagation();
   }
 }
 
 document.addEventListener("dialogaccept", function(event) {
-  dlgClose('accept');
+  dlgClose("accept");
 });
--- a/mail/extensions/openpgp/content/ui/enigmailMsgComposeHelper.js
+++ b/mail/extensions/openpgp/content/ui/enigmailMsgComposeHelper.js
@@ -1,137 +1,202 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 /**
  * helper functions for message composition
  */
 
-var EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-var EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-var EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-var EnigmailTrust = ChromeUtils.import("chrome://openpgp/content/modules/trust.jsm").EnigmailTrust;
-var EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-var EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
+var EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm")
+  .EnigmailLog;
+var EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+var EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm")
+  .EnigmailGpg;
+var EnigmailTrust = ChromeUtils.import(
+  "chrome://openpgp/content/modules/trust.jsm"
+).EnigmailTrust;
+var EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+var EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
 
-if (!Enigmail) var Enigmail = {};
+if (!Enigmail) {
+  var Enigmail = {};
+}
 
 Enigmail.hlp = {
-
   /* try to find valid key to passed email addresses (or keys)
    * @return: list of all found key (with leading "0x") or null
    *          details in details parameter
    */
-  validKeysForAllRecipients: function(emailsOrKeys, details) {
+  validKeysForAllRecipients(emailsOrKeys, details) {
     EnigmailLog.DEBUG("=====> validKeysForAllRecipients()\n");
-    EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: validKeysForAllRecipients(): emailsOrKeys='" + emailsOrKeys + "'\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeHelper.js: validKeysForAllRecipients(): emailsOrKeys='" +
+        emailsOrKeys +
+        "'\n"
+    );
 
     // use helper to see when we enter and leave this function
-    let resultingArray = this.doValidKeysForAllRecipients(emailsOrKeys, details);
+    let resultingArray = this.doValidKeysForAllRecipients(
+      emailsOrKeys,
+      details
+    );
 
-    EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: validKeysForAllRecipients(): return '" + resultingArray + "'\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeHelper.js: validKeysForAllRecipients(): return '" +
+        resultingArray +
+        "'\n"
+    );
     EnigmailLog.DEBUG("  <=== validKeysForAllRecipients()\n");
     return resultingArray;
   },
 
-
   // helper for validKeysForAllRecipients()
-  doValidKeysForAllRecipients: function(emailsOrKeys, details) {
-    EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): emailsOrKeys='" + emailsOrKeys + "'\n");
+  doValidKeysForAllRecipients(emailsOrKeys, details) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): emailsOrKeys='" +
+        emailsOrKeys +
+        "'\n"
+    );
 
     // check which keys are accepted
     let minTrustLevel;
     let acceptedKeys = EnigmailPrefs.getPref("acceptedKeys");
     switch (acceptedKeys) {
       case 0: // accept valid/authenticated keys only
         minTrustLevel = "f"; // first value for trusted keys
         break;
       case 1: // accept all but revoked/disabled/expired keys
         minTrustLevel = "?"; // value between invalid and unknown keys
         break;
       default:
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: doValidKeysForAllRecipients(): return null (INVALID VALUE for acceptedKeys: \"" + acceptedKeys + "\")\n");
+        EnigmailLog.DEBUG(
+          'enigmailMsgComposeOverlay.js: doValidKeysForAllRecipients(): return null (INVALID VALUE for acceptedKeys: "' +
+            acceptedKeys +
+            '")\n'
+        );
         return null;
     }
 
-    EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): find keys with minTrustLevel=\"" + minTrustLevel + "\"\n");
+    EnigmailLog.DEBUG(
+      'enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): find keys with minTrustLevel="' +
+        minTrustLevel +
+        '"\n'
+    );
 
     let keyMissing;
     let resultingArray = []; // resulting key list (if all valid)
     try {
       // create array of address elements (email or key)
       let addresses = [];
       try {
-        addresses = EnigmailFuncs.stripEmail(emailsOrKeys).split(',');
+        addresses = EnigmailFuncs.stripEmail(emailsOrKeys).split(",");
       } catch (ex) {}
 
       // resolve all the email addresses if possible:
-      keyMissing = EnigmailKeyRing.getValidKeysForAllRecipients(addresses, minTrustLevel, details, resultingArray);
+      keyMissing = EnigmailKeyRing.getValidKeysForAllRecipients(
+        addresses,
+        minTrustLevel,
+        details,
+        resultingArray
+      );
     } catch (ex) {
-      EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): return null (exception: " + ex.message + "\n" + ex.stack + ")\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): return null (exception: " +
+          ex.message +
+          "\n" +
+          ex.stack +
+          ")\n"
+      );
       return null;
     }
     if (keyMissing) {
-      EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): return null (key missing)\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): return null (key missing)\n"
+      );
       return null;
     }
-    EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): return \"" + resultingArray + "\"\n");
+    EnigmailLog.DEBUG(
+      'enigmailMsgComposeHelper.js: doValidKeysForAllRecipients(): return "' +
+        resultingArray +
+        '"\n'
+    );
     return resultingArray;
   },
 
-
   /**
    * processConflicts
    * - handle sign/encrypt/pgpMime conflicts if any
    * - NOTE: conflicts result into disabling the feature (0/never)
    * Input parameters:
    *  @encrypt: email would currently get encrypted
    *  @sign:    email would currently get signed
    * @return:  false if error occurred or processing was canceled
    */
-  processConflicts: function(encrypt, sign) {
+  processConflicts(encrypt, sign) {
     // process message about whether we still sign/encrypt
     let msg = "";
-    msg += "\n- " + EnigmailLocale.getString(encrypt ? "encryptYes" : "encryptNo");
+    msg +=
+      "\n- " + EnigmailLocale.getString(encrypt ? "encryptYes" : "encryptNo");
     msg += "\n- " + EnigmailLocale.getString(sign ? "signYes" : "signNo");
     if (EnigmailPrefs.getPref("warnOnRulesConflict") == 2) {
       EnigmailPrefs.setPref("warnOnRulesConflict", 0);
     }
-    if (!EnigmailDialog.confirmPref(window, EnigmailLocale.getString("rulesConflict", [msg]), "warnOnRulesConflict")) {
+    if (
+      !EnigmailDialog.confirmPref(
+        window,
+        EnigmailLocale.getString("rulesConflict", [msg]),
+        "warnOnRulesConflict"
+      )
+    ) {
       return false;
     }
     return true;
   },
 
-
   /**
    * determine invalid recipients as returned from GnuPG
    *
    * @gpgMsg: output from GnuPG
    *
    * @return: space separated list of invalid addresses
    */
-  getInvalidAddress: function(gpgMsg) {
-    EnigmailLog.DEBUG("enigmailMsgComposeHelper.js: getInvalidAddress(): gpgMsg=\"" + gpgMsg + "\"\n\n");
+  getInvalidAddress(gpgMsg) {
+    EnigmailLog.DEBUG(
+      'enigmailMsgComposeHelper.js: getInvalidAddress(): gpgMsg="' +
+        gpgMsg +
+        '"\n\n'
+    );
     var invalidAddr = [];
     var lines = gpgMsg.split(/[\n\r]+/);
     for (var i = 0; i < lines.length; i++) {
       var m = lines[i].match(/^(INV_RECP \d+ )(.*)$/);
       if (m && m.length == 3) {
         try {
           invalidAddr.push(EnigmailFuncs.stripEmail(m[2].toLowerCase()));
         } catch (ex) {}
       }
     }
     return invalidAddr.join(" ");
-  }
-
+  },
 };
--- a/mail/extensions/openpgp/content/ui/enigmailMsgComposeOverlay.js
+++ b/mail/extensions/openpgp/content/ui/enigmailMsgComposeOverlay.js
@@ -1,74 +1,123 @@
-/*global EnigmailLocale: false, EnigmailApp: false, Dialog: false, EnigmailTimer: false */
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 /*globally available Thunderbird variables/object/functions: */
 /*global gMsgCompose: false, getCurrentIdentity: false, gNotification: false */
 /*global UpdateAttachmentBucket: false, gContentChanged: true */
 /*global AddAttachments: false, AddAttachment: false, ChangeAttachmentBucketVisibility: false, GetResourceFromUri: false */
 /*global Recipients2CompFields: false, Attachments2CompFields: false, DetermineConvertibility: false, gWindowLocked: false */
 /*global CommandUpdate_MsgCompose: false, gSMFields: false, setSecuritySettings: false, getCurrentAccountKey: false */
 /*global Sendlater3Composing: false, MailServices: false */
-
-var EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-var EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-var EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-var EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-var EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-var EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-var EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-var EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-var EnigmailURIs = ChromeUtils.import("chrome://openpgp/content/modules/uris.jsm").EnigmailURIs;
-var EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-var EnigmailDecryption = ChromeUtils.import("chrome://openpgp/content/modules/decryption.jsm").EnigmailDecryption;
-var EnigmailEncryption = ChromeUtils.import("chrome://openpgp/content/modules/encryption.jsm").EnigmailEncryption;
-var EnigmailClipboard = ChromeUtils.import("chrome://openpgp/content/modules/clipboard.jsm").EnigmailClipboard;
-var EnigmailWkdLookup = ChromeUtils.import("chrome://openpgp/content/modules/wkdLookup.jsm").EnigmailWkdLookup;
-var EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
-var EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-var EnigmailMsgRead = ChromeUtils.import("chrome://openpgp/content/modules/msgRead.jsm").EnigmailMsgRead;
-var EnigmailMimeEncrypt = ChromeUtils.import("chrome://openpgp/content/modules/mimeEncrypt.jsm").EnigmailMimeEncrypt;
+/*global gSendEncrypted: true, gOptionalEncryption: true, gSendSigned: true, gSelectedTechnologyIsPGP: true */
+/*global gIsRelatedToEncryptedOriginal: true, gIsRelatedToSignedOriginal: true, gAttachMyPublicPGPKey: true */
+
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
+
+var EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm")
+  .EnigmailLog;
+var EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+var EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+  .EnigmailOS;
+var EnigmailArmor = ChromeUtils.import(
+  "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailFiles = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+var EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+var EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm")
+  .EnigmailApp;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+var EnigmailTimer = ChromeUtils.import(
+  "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+var EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+var EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+var EnigmailURIs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/uris.jsm"
+).EnigmailURIs;
+var EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+var EnigmailDecryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/decryption.jsm"
+).EnigmailDecryption;
+var EnigmailEncryption = ChromeUtils.import(
+  "chrome://openpgp/content/modules/encryption.jsm"
+).EnigmailEncryption;
+var EnigmailClipboard = ChromeUtils.import(
+  "chrome://openpgp/content/modules/clipboard.jsm"
+).EnigmailClipboard;
+var EnigmailWkdLookup = ChromeUtils.import(
+  "chrome://openpgp/content/modules/wkdLookup.jsm"
+).EnigmailWkdLookup;
+var EnigmailAutocrypt = ChromeUtils.import(
+  "chrome://openpgp/content/modules/autocrypt.jsm"
+).EnigmailAutocrypt;
+var EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+var EnigmailMsgRead = ChromeUtils.import(
+  "chrome://openpgp/content/modules/msgRead.jsm"
+).EnigmailMsgRead;
+var EnigmailMimeEncrypt = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mimeEncrypt.jsm"
+).EnigmailMimeEncrypt;
 var jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
 
 // Account encryption policy values:
 // const kEncryptionPolicy_Never = 0;
 // 'IfPossible' was used by ns4.
 // const kEncryptionPolicy_IfPossible = 1;
 var kEncryptionPolicy_Always = 2;
 
-if (!Enigmail) var Enigmail = {};
+if (!Enigmail) {
+  var Enigmail = {};
+}
 
 const IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
 const LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";
 
 Enigmail.msg = {
   editor: null,
   dirty: null, // inconsistent, other places use int. should this be zero ?
-               // dirty means: composer contents were modified by this code, right?
+  // dirty means: composer contents were modified by this code, right?
   processed: null, // contains information for undo of inline signed/encrypt
   timeoutId: null, // TODO: once set, it's never reset
   sendPgpMime: true,
   //sendMode: null, // the current default for sending a message (0, SIGN, ENCRYPT, or SIGN|ENCRYPT)
   //sendModeDirty: false, // send mode or final send options changed?
 
-  
   // processed strings to signal final encrypt/sign/pgpmime state:
   statusEncryptedStr: "???",
   statusSignedStr: "???",
   //statusPGPMimeStr: "???",
   //statusSMimeStr: "???",
   //statusInlinePGPStr: "???",
   statusAttachOwnKey: "???",
 
@@ -78,49 +127,51 @@ Enigmail.msg = {
   modifiedAttach: null,
   lastFocusedWindow: null,
   determineSendFlagId: null,
   trustAllKeys: false,
   protectHeaders: false,
   draftSubjectEncrypted: false,
   attachOwnKeyObj: {
     attachedObj: null,
-    attachedKey: null
+    attachedKey: null,
   },
 
   keyLookupDone: [],
 
   saveDraftError: 0,
   addrOnChangeTimeout: 250,
   /* timeout when entering something into the address field */
 
-  composeStartup: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.composeStartup\n");
-
-    function addSecurityListener(itemId, func) {
-      let s = document.getElementById(itemId);
-      if (s) {
-        s.addEventListener("command", func.bind(Enigmail.msg), false);
-      }
-      else {
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: addSecurityListener - cannot find element " + itemId + "\n");
-      }
-    }
+  composeStartup() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.composeStartup\n"
+    );
 
     if (!gMsgCompose || !gMsgCompose.compFields) {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: no gMsgCompose, leaving\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: no gMsgCompose, leaving\n"
+      );
       return;
     }
 
     gMsgCompose.RegisterStateListener(Enigmail.composeStateListener);
     Enigmail.msg.composeBodyReady = false;
 
     // Listen to message sending event
-    addEventListener("compose-send-message", Enigmail.msg.sendMessageListener.bind(Enigmail.msg), true);
-    addEventListener("compose-from-changed", Enigmail.msg.fromChangedListener.bind(Enigmail.msg), true);
+    addEventListener(
+      "compose-send-message",
+      Enigmail.msg.sendMessageListener.bind(Enigmail.msg),
+      true
+    );
+    addEventListener(
+      "compose-from-changed",
+      Enigmail.msg.fromChangedListener.bind(Enigmail.msg),
+      true
+    );
 
     // Relabel SMIME button and menu item
     //var smimeButton = document.getElementById("button-security");
     //let toolbar = document.getElementById("composeToolbar2");
 
     /*
     if (smimeButton) {
       smimeButton.setAttribute("label", "S/MIME");
@@ -128,83 +179,83 @@ Enigmail.msg = {
         // remove S/MIME button if the toolbar is displaying the default set
         toolbar.removeChild(smimeButton);
       }
     }
     */
 
     var msgId = document.getElementById("msgIdentityPopup");
     if (msgId) {
-      msgId.addEventListener("command", Enigmail.msg.setIdentityCallback, false);
+      msgId.addEventListener("command", Enigmail.msg.setIdentityCallback);
     }
 
     var subj = document.getElementById("msgSubject");
-    subj.addEventListener('focus', Enigmail.msg.fireSendFlags, false);
+    subj.addEventListener("focus", Enigmail.msg.fireSendFlags);
 
     /*
     let numCerts = EnigmailFuncs.getNumOfX509Certs();
     this.addrOnChangeTimeout = Math.max((numCerts - 250) * 2, 250);
     EnigmailLog.DEBUG(`enigmailMsgComposeOverlay.js: composeStartup: numCerts=${numCerts}; setting timeout to ${this.addrOnChangeTimeout}\n`);
     */
 
     Enigmail.msg.msgComposeReset(false); // false => not closing => call setIdentityDefaults()
 
     // TODO this migration code needs to move to a better place, possibly configure.jsm
     {
       // Use a new pref identityEnigmailPrefsMigrated, default false.
       // Only if we're doing this for the first time for an identity,
       // try to read old prefs and if found, store as new prefs,
       // then set identityEnigmailPrefsMigrated=true
 
-      if (Enigmail.msg.wasEnigmailAddOnInstalled() &&
-          Enigmail.msg.wasEnigmailEnabledForIdentity() &&
-          this.identity.getIntAttribute("mimePreferOpenPGP") > 0) {
+      if (
+        Enigmail.msg.wasEnigmailAddOnInstalled() &&
+        Enigmail.msg.wasEnigmailEnabledForIdentity() &&
+        this.identity.getIntAttribute("mimePreferOpenPGP") > 0
+      ) {
         // migrate old enigmail prefs
-        gSendEncrypted = (this.identity.getIntAttribute("defaultEncryptionPolicy") > 0);
-        gOptionalEncryption = (this.identity.getIntAttribute("autoSendEncrypted") > 0);
-        gSendSigned = (this.identity.getIntAttribute("defaultSigningPolicy") > 0);
+        gSendEncrypted =
+          this.identity.getIntAttribute("defaultEncryptionPolicy") > 0;
+        gOptionalEncryption =
+          this.identity.getIntAttribute("autoSendEncrypted") > 0;
+        gSendSigned = this.identity.getIntAttribute("defaultSigningPolicy") > 0;
         gSelectedTechnologyIsPGP = true;
+      } else if (Enigmail.msg.isSmimeEnabled()) {
+        gSendEncrypted = this.identity.getIntAttribute("encryptionpolicy") > 0;
+        gOptionalEncryption = false;
+        gSendSigned = this.identity.getBoolAttribute("sign_mail");
       } else {
-        if (Enigmail.msg.isSmimeEnabled()) {
-          gSendEncrypted = (this.identity.getIntAttribute("encryptionpolicy") > 0);
-          gOptionalEncryption = false;
-          gSendSigned = (this.identity.getBoolAttribute("sign_mail"));
-        } else {
-          // if the user didn't yet configure s/mime, use PGP mode.
-          gSendEncrypted = false;
-          gOptionalEncryption = false;
-          gSendSigned = false;
-          gSelectedTechnologyIsPGP = true;
-        }
+        // if the user didn't yet configure s/mime, use PGP mode.
+        gSendEncrypted = false;
+        gOptionalEncryption = false;
+        gSendSigned = false;
+        gSelectedTechnologyIsPGP = true;
       }
-      
+
       // TODO: If already migrated, set variables using new pres
     }
 
     if (gIsRelatedToEncryptedOriginal) {
       gSendEncrypted = true;
     }
-  
+
     if (!gSelectedTechnologyIsPGP) {
       gSMFields.requireEncryptMessage = gSendEncrypted;
       gSMFields.signMessage = gSendSigned;
     }
 
-
     Enigmail.msg.composeOpen();
     //Enigmail.msg.processFinalState();
     Enigmail.msg.updateStatusBar();
     Enigmail.msg.initialSendFlags();
 
     //Enigmail.msg.setFinalSendMode('final-pgpmimeYes');
   },
 
-
   // TODO: call this from global compose when options change
-  enigmailComposeProcessFinalState: function() {
+  enigmailComposeProcessFinalState() {
     //Enigmail.msg.processFinalState();
     Enigmail.msg.updateStatusBar();
   },
 
   /*
   handleClick: function(event, modifyType) {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.handleClick\n");
     switch (event.button) {
@@ -216,27 +267,28 @@ Enigmail.msg = {
         break;
       case 0:
         this.doPgpButton(modifyType);
         break;
     }
   },
   */
 
-
-  setIdentityCallback: function(elementId) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setIdentityCallback: elementId=" + elementId + "\n");
-
-    EnigmailTimer.setTimeout(function _f() {
-        Enigmail.msg.setIdentityDefaults();
-      },
-      100);
+  setIdentityCallback(elementId) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.setIdentityCallback: elementId=" +
+        elementId +
+        "\n"
+    );
+
+    EnigmailTimer.setTimeout(function() {
+      Enigmail.msg.setIdentityDefaults();
+    }, 100);
   },
 
-
   /* return whether the account specific setting key is enabled or disabled
    */
   /*
   getAccDefault: function(key) {
     //EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.getAccDefault: identity="+this.identity.key+"("+this.identity.email+") key="+key+"\n");
     let res = null;
     let mimePreferOpenPGP = this.identity.getIntAttribute("mimePreferOpenPGP");
     let isSmimeEnabled = Enigmail.msg.isSmimeEnabled();
@@ -315,21 +367,23 @@ Enigmail.msg = {
   isAnyEncryptionEnabled: function() {
     let id = getCurrentIdentity();
 
     return ((id.getUnicharAttribute("encryption_cert_name") !== "") ||
       Enigmail.msg.wasEnigmailEnabledForIdentity());
   },
   */
 
-  isSmimeEnabled: function() {
+  isSmimeEnabled() {
     let id = getCurrentIdentity();
 
-    return ((id.getUnicharAttribute("signing_cert_name") !== "") ||
-      (id.getUnicharAttribute("encryption_cert_name") !== ""));
+    return (
+      id.getUnicharAttribute("signing_cert_name") !== "" ||
+      id.getUnicharAttribute("encryption_cert_name") !== ""
+    );
   },
 
   /**
    * Determine if any of Enigmail (OpenPGP) or S/MIME signing is enabled for the account
    */
   /*
   getSigningEnabled: function() {
     let id = getCurrentIdentity();
@@ -344,18 +398,20 @@ Enigmail.msg = {
     let id = getCurrentIdentity();
 
     if (!id.getUnicharAttribute("signing_cert_name")) return false;
 
     return id.getBoolAttribute("sign_mail");
   },
   */
 
-  setIdentityDefaults: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setIdentityDefaults\n");
+  setIdentityDefaults() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.setIdentityDefaults\n"
+    );
 
     this.identity = getCurrentIdentity();
 
     if (!Enigmail.msg.isEnigmailEnabledForIdentity()) {
       // reset status strings in menu to useful defaults
       this.statusEncryptedStr = EnigmailLocale.getString("encryptNo");
       this.statusSignedStr = EnigmailLocale.getString("signNo", [""]);
       //this.statusPGPMimeStr = EnigmailLocale.getString("pgpmimeNormal");
@@ -374,17 +430,16 @@ Enigmail.msg = {
       //this.processAccountSpecificDefaultOptions();
       this.determineSendFlags(); // important to use identity specific settings
       //this.processFinalState();
       this.updateStatusBar();
     }
     */
   },
 
-
   /*
   // set the current default for sending a message
   // depending on the identity
   processAccountSpecificDefaultOptions: function() {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.processAccountSpecificDefaultOptions\n");
 
     const SIGN = EnigmailConstants.SEND_SIGNED;
     const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
@@ -412,93 +467,111 @@ Enigmail.msg = {
     this.setOwnKeyStatus();
     this.attachOwnKeyObj.attachedObj = null;
     this.attachOwnKeyObj.attachedKey = null;
 
     //this.finalSignDependsOnEncrypt = (this.getAccDefault("signIfEnc") || this.getAccDefault("signIfNotEnc"));
   },
   */
 
-  getOriginalMsgUri: function() {
+  getOriginalMsgUri() {
     let draftId = gMsgCompose.compFields.draftId;
     let msgUri = null;
 
-    if (typeof(draftId) == "string" && draftId.length > 0) {
+    if (typeof draftId == "string" && draftId.length > 0) {
       // original message is draft
       msgUri = draftId.replace(/\?.*$/, "");
-    }
-    else if (typeof(gMsgCompose.originalMsgURI) == "string" && gMsgCompose.originalMsgURI.length > 0) {
+    } else if (
+      typeof gMsgCompose.originalMsgURI == "string" &&
+      gMsgCompose.originalMsgURI.length > 0
+    ) {
       // original message is a "true" mail
       msgUri = gMsgCompose.originalMsgURI;
     }
 
     return msgUri;
   },
 
-  getMsgHdr: function(msgUri) {
+  getMsgHdr(msgUri) {
     if (!msgUri) {
       msgUri = this.getOriginalMsgUri();
     }
     if (msgUri) {
-      let messenger = Components.classes["@mozilla.org/messenger;1"].getService(Components.interfaces.nsIMessenger);
+      let messenger = Cc["@mozilla.org/messenger;1"].getService(
+        Ci.nsIMessenger
+      );
       return messenger.messageServiceFromURI(msgUri).messageURIToMsgHdr(msgUri);
     }
-    else return null;
+    return null;
   },
 
-  getMsgProperties: function(draft) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: Enigmail.msg.getMsgProperties:\n");
+  getMsgProperties(draft) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: Enigmail.msg.getMsgProperties:\n"
+    );
 
     let msgUri = this.getOriginalMsgUri();
     let self = this;
     let properties = 0;
     try {
       let msgHdr = this.getMsgHdr(msgUri);
       if (msgHdr) {
         let msgUrl = EnigmailMsgRead.getUrlFromUriSpec(msgUri);
         properties = msgHdr.getUint32Property("enigmail");
         try {
-          EnigmailMime.getMimeTreeFromUrl(msgUrl.spec, false, function _cb(mimeMsg) {
+          EnigmailMime.getMimeTreeFromUrl(msgUrl.spec, false, function(
+            mimeMsg
+          ) {
             if (draft) {
               self.setDraftOptions(mimeMsg);
-              if (self.draftSubjectEncrypted) self.setOriginalSubject(msgHdr.subject, false);
-            }
-            else {
-              if (EnigmailURIs.isEncryptedUri(msgUri)) self.setOriginalSubject(msgHdr.subject, false);
+              if (self.draftSubjectEncrypted) {
+                self.setOriginalSubject(msgHdr.subject, false);
+              }
+            } else if (EnigmailURIs.isEncryptedUri(msgUri)) {
+              self.setOriginalSubject(msgHdr.subject, false);
             }
           });
-        }
-        catch (ex) {
-          EnigmailLog.DEBUG("enigmailMessengerOverlay.js: Enigmail.msg.getMsgProperties: excetion in getMimeTreeFromUrl\n");
+        } catch (ex) {
+          EnigmailLog.DEBUG(
+            "enigmailMessengerOverlay.js: Enigmail.msg.getMsgProperties: excetion in getMimeTreeFromUrl\n"
+          );
         }
       }
-    }
-    catch (ex) {
-      EnigmailLog.DEBUG("enigmailMessengerOverlay.js: Enigmail.msg.getMsgProperties: got exception '" + ex.toString() + "'\n");
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "enigmailMessengerOverlay.js: Enigmail.msg.getMsgProperties: got exception '" +
+          ex.toString() +
+          "'\n"
+      );
     }
 
     if (EnigmailURIs.isEncryptedUri(msgUri)) {
       properties |= EnigmailConstants.DECRYPTION_OKAY;
     }
 
     return properties;
   },
 
-  setDraftOptions: function(mimeMsg) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setDraftOptions\n");
+  setDraftOptions(mimeMsg) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.setDraftOptions\n"
+    );
 
     var stat = "";
     if (mimeMsg && mimeMsg.headers.has("x-enigmail-draft-status")) {
       stat = String(mimeMsg.headers.get("x-enigmail-draft-status").join(""));
-    }
-    else {
+    } else {
       return;
     }
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setDraftOptions: draftStatus: " + stat + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.setDraftOptions: draftStatus: " +
+        stat +
+        "\n"
+    );
 
     // TODO: rewrite to properly read old draft header information
     /*
     if (stat.substr(0, 1) == "N") {
       // new style drafts (Enigmail 1.7)
 
       var enc = "final-encryptDefault";
       switch (Number(stat.substr(1, 1))) {
@@ -543,36 +616,39 @@ Enigmail.msg = {
       if (flags & EnigmailConstants.SEND_ENCRYPTED) Enigmail.msg.setFinalSendMode('final-encryptYes');
       if (flags & EnigmailConstants.SEND_ATTACHMENT)
         Enigmail.msg.attachOwnKeyObj.appendAttachment = true;
     }
     //Enigmail.msg.setOwnKeyStatus();
     */
   },
 
-  setOriginalSubject: function(subject, forceSetting) {
-    const CT = Components.interfaces.nsIMsgCompType;
+  setOriginalSubject(subject, forceSetting) {
+    const CT = Ci.nsIMsgCompType;
     let subjElem = document.getElementById("msgSubject");
     let prefix = "";
 
-    if (!subjElem) return;
+    if (!subjElem) {
+      return;
+    }
 
     switch (gMsgCompose.type) {
       case CT.ForwardInline:
       case CT.ForwardAsAttachment:
         prefix = this.getMailPref("mail.forward_subject_prefix") + ": ";
         break;
       case CT.Reply:
       case CT.ReplyAll:
       case CT.ReplyToSender:
       case CT.ReplyToGroup:
       case CT.ReplyToSenderAndGroup:
       case CT.ReplyToList:
-        if (!subject.startsWith("Re: "))
+        if (!subject.startsWith("Re: ")) {
           prefix = "Re: ";
+        }
     }
 
     let doSetSubject = forceSetting;
     switch (gMsgCompose.type) {
       case CT.Draft:
       case CT.Template:
       case CT.EditTemplate:
       case CT.ForwardInline:
@@ -581,219 +657,249 @@ Enigmail.msg = {
         doSetSubject = true;
         break;
     }
 
     if (doSetSubject) {
       subject = EnigmailData.convertToUnicode(subject, "UTF-8");
       subject = jsmime.headerparser.decodeRFC2047Words(subject, "utf-8");
 
-      if (subjElem.value == "Re: " + subject) return;
+      if (subjElem.value == "Re: " + subject) {
+        return;
+      }
 
       gMsgCompose.compFields.subject = prefix + subject;
       subjElem.value = prefix + subject;
-      if (typeof subjElem.oninput === "function") subjElem.oninput();
+      if (typeof subjElem.oninput === "function") {
+        subjElem.oninput();
+      }
     }
   },
 
-  setupMenuAndToolbar: function() {
-    return;
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setupMenuAndToolbar\n");
+  setupMenuAndToolbar() {
+    /*
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.setupMenuAndToolbar\n"
+    );
     let toolbarTxt = document.getElementById("enigmail-toolbar-text");
     let encBroadcaster = document.getElementById("enigmail-bc-encrypt");
     let signBroadcaster = document.getElementById("enigmail-bc-sign");
     let attachBroadcaster = document.getElementById("enigmail-bc-attach");
     let enigmailMenu = document.getElementById("menu_Enigmail");
 
     encBroadcaster.removeAttribute("hidden");
     signBroadcaster.removeAttribute("hidden");
     attachBroadcaster.removeAttribute("hidden");
     if (toolbarTxt) {
       toolbarTxt.removeAttribute("hidden");
     }
     enigmailMenu.removeAttribute("hidden");
+    */
   },
 
-  composeOpen: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.composeOpen\n");
-
-    const SIGN = EnigmailConstants.SEND_SIGNED;
-    const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
+  composeOpen() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.composeOpen\n"
+    );
 
     var msgFlags;
     var msgUri = null;
     var msgIsDraft = false;
 
     this.setupMenuAndToolbar();
 
     this.determineSendFlagId = null;
     //this.disableSmime = false;
     this.saveDraftError = 0;
-    this.protectHeaders = (EnigmailPrefs.getPref("protectedHeaders") === 2);
+    this.protectHeaders = EnigmailPrefs.getPref("protectedHeaders") === 2;
     //this.enableUndoEncryption(false);
 
     this.displayProtectHeadersStatus();
 
     var toobarElem = document.getElementById("composeToolbar2");
-    if (toobarElem && (EnigmailOS.getOS() == "Darwin")) {
+    if (toobarElem && EnigmailOS.getOS() == "Darwin") {
       toobarElem.setAttribute("platform", "macos");
     }
 
     /*
     // remove overlay_source from enigmail-bc-sendprocess, which will be inherited to
     // addressCol2 and addressCol1 (those would be removed if Enigmail is uninstalled)
     let bc = document.getElementById("enigmail-bc-sendprocess");
     bc.removeAttribute("overlay_source");
     */
 
     // Thunderbird
     var adrCol = document.getElementById("addressCol2#1"); // recipients field
     if (adrCol) {
       let attr = adrCol.getAttribute("oninput");
-      adrCol.setAttribute("oninput", attr + "; Enigmail.msg.addressOnChange();");
+      adrCol.setAttribute(
+        "oninput",
+        attr + "; Enigmail.msg.addressOnChange();"
+      );
       attr = adrCol.getAttribute("onchange");
-      adrCol.setAttribute("onchange", attr + "; Enigmail.msg.addressOnChange();");
+      adrCol.setAttribute(
+        "onchange",
+        attr + "; Enigmail.msg.addressOnChange();"
+      );
       //adrCol.setAttribute("observes", "enigmail-bc-sendprocess");
     }
     adrCol = document.getElementById("addressCol1#1"); // to/cc/bcc/... field
     if (adrCol) {
       let attr = adrCol.getAttribute("oncommand");
-      adrCol.setAttribute("oncommand", attr + "; Enigmail.msg.addressOnChange();");
+      adrCol.setAttribute(
+        "oncommand",
+        attr + "; Enigmail.msg.addressOnChange();"
+      );
       //adrCol.setAttribute("observes", "enigmail-bc-sendprocess");
     }
 
     var draftId = gMsgCompose.compFields.draftId;
     let selectedElement = document.activeElement;
 
     //if (EnigmailPrefs.getPref("keepSettingsForReply") && (!(this.sendMode & ENCRYPT)) || (typeof(draftId) == "string" && draftId.length > 0)) {
-    if (typeof(draftId) == "string" && draftId.length > 0) {
-
+    if (typeof draftId == "string" && draftId.length > 0) {
       /* global gEncryptedURIService: false */
       /*
       if (gEncryptedURIService && gEncryptedURIService.isEncrypted(gMsgCompose.originalMsgURI)) {
         // Enable S/MIME encryption if original is known as encrypted.
         //this.setFinalSendMode('final-encryptYes');
       }
       */
       msgUri = this.getOriginalMsgUri();
 
-      if (typeof(draftId) == "string" && draftId.length > 0) {
+      if (typeof draftId == "string" && draftId.length > 0) {
         // original message is draft
         msgIsDraft = true;
       }
 
       if (msgUri) {
         msgFlags = this.getMsgProperties(msgIsDraft);
         if (!msgIsDraft) {
           if (msgFlags & EnigmailConstants.DECRYPTION_OKAY) {
-            EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.composeOpen: has encrypted originalMsgUri\n");
-            EnigmailLog.DEBUG("originalMsgURI=" + gMsgCompose.originalMsgURI + "\n");
+            EnigmailLog.DEBUG(
+              "enigmailMsgComposeOverlay.js: Enigmail.msg.composeOpen: has encrypted originalMsgUri\n"
+            );
+            EnigmailLog.DEBUG(
+              "originalMsgURI=" + gMsgCompose.originalMsgURI + "\n"
+            );
             //this.setFinalSendMode('final-encryptYes');
             gIsRelatedToEncryptedOriginal = true;
 
             this.identity = getCurrentIdentity();
             if (this.identity.getBoolAttribute("pgpSignEncrypted")) {
               //this.setFinalSendMode('final-signYes');
             }
 
             //this.disableSmime = true;
-          }
-          else if (msgFlags & (EnigmailConstants.GOOD_SIGNATURE |
+          } else if (
+            msgFlags &
+            (EnigmailConstants.GOOD_SIGNATURE |
               EnigmailConstants.BAD_SIGNATURE |
-              EnigmailConstants.UNVERIFIED_SIGNATURE)) {
+              EnigmailConstants.UNVERIFIED_SIGNATURE)
+          ) {
             //this.setSendMode('sign');
             gIsRelatedToSignedOriginal = true;
           }
         }
         this.removeAttachedKey();
       }
     }
 
     // check for attached signature files and remove them
     var bucketList = document.getElementById("attachmentBucket");
     if (bucketList.hasChildNodes()) {
       var node = bucketList.firstChild;
-      let nodeNumber = 0;
       while (node) {
         if (node.attachment.contentType == "application/pgp-signature") {
           if (!this.findRelatedAttachment(bucketList, node)) {
             // Let's release the attachment object held by the node else it won't go away until the window is destroyed
             node.attachment = null;
             node = bucketList.removeChild(node);
           }
         }
-        else {
-          ++nodeNumber;
-        }
         node = node.nextSibling;
       }
       if (!bucketList.hasChildNodes()) {
         try {
           // TB only
           UpdateAttachmentBucket(false);
-        }
-        catch (ex) {}
+        } catch (ex) {}
       }
     }
 
     try {
       // TB only
       UpdateAttachmentBucket(bucketList.hasChildNodes());
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     //this.processFinalState();
     this.updateStatusBar();
-    if (selectedElement) selectedElement.focus();
+    if (selectedElement) {
+      selectedElement.focus();
+    }
   },
 
   // check if an signature is related to another attachment
-  findRelatedAttachment: function(bucketList, node) {
-
+  findRelatedAttachment(bucketList, node) {
     // check if filename ends with .sig
-    if (node.attachment.name.search(/\.sig$/i) < 0) return null;
+    if (node.attachment.name.search(/\.sig$/i) < 0) {
+      return null;
+    }
 
     var relatedNode = bucketList.firstChild;
     var findFile = node.attachment.name.toLowerCase();
     var baseAttachment = null;
     while (relatedNode) {
-      if (relatedNode.attachment.name.toLowerCase() + ".sig" == findFile)
+      if (relatedNode.attachment.name.toLowerCase() + ".sig" == findFile) {
         baseAttachment = relatedNode.attachment;
+      }
       relatedNode = relatedNode.nextSibling;
     }
     return baseAttachment;
   },
 
-  initialSendFlags: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.initialSendFlags\n");
+  initialSendFlags() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.initialSendFlags\n"
+    );
     this.fireSendFlags();
 
-    EnigmailTimer.setTimeout(function _f() {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay: re-determine send flags\n");
-      try {
-        this.determineSendFlags();
-        //this.processFinalState();
-        this.updateStatusBar();
-      }
-      catch (ex) {
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay: re-determine send flags - ERROR: " + ex.toString() + "\n");
-      }
-    }.bind(Enigmail.msg), 1500);
+    EnigmailTimer.setTimeout(
+      function() {
+        EnigmailLog.DEBUG(
+          "enigmailMsgComposeOverlay: re-determine send flags\n"
+        );
+        try {
+          this.determineSendFlags();
+          //this.processFinalState();
+          this.updateStatusBar();
+        } catch (ex) {
+          EnigmailLog.DEBUG(
+            "enigmailMsgComposeOverlay: re-determine send flags - ERROR: " +
+              ex.toString() +
+              "\n"
+          );
+        }
+      }.bind(Enigmail.msg),
+      1500
+    );
   },
 
-
-  msgComposeClose: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.msgComposeClose\n");
+  msgComposeClose() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.msgComposeClose\n"
+    );
 
     this.msgComposeReset(true); // true => closing => don't call setIdentityDefaults()
   },
 
-
-  msgComposeReset: function(closing) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.msgComposeReset\n");
+  msgComposeReset(closing) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.msgComposeReset\n"
+    );
 
     this.dirty = 0;
     this.processed = null;
     this.timeoutId = null;
 
     this.modifiedAttach = null;
     //this.sendMode = 0;
     //this.sendModeDirty = false;
@@ -816,33 +922,36 @@ Enigmail.msg = {
     //this.mimePreferOpenPGP = 0;
     this.keyLookupDone = [];
 
     if (!closing) {
       this.setIdentityDefaults();
     }
   },
 
-
-  initRadioMenu: function(prefName, optionIds) {
-    EnigmailLog.DEBUG("enigmailMessengerOverlay.js: Enigmail.msg.initRadioMenu: " + prefName + "\n");
-
-    var encryptId;
+  initRadioMenu(prefName, optionIds) {
+    EnigmailLog.DEBUG(
+      "enigmailMessengerOverlay.js: Enigmail.msg.initRadioMenu: " +
+        prefName +
+        "\n"
+    );
 
     var prefValue = EnigmailPrefs.getPref(prefName);
 
-    if (prefValue >= optionIds.length)
+    if (prefValue >= optionIds.length) {
       return;
+    }
 
     var menuItem = document.getElementById("enigmail_" + optionIds[prefValue]);
-    if (menuItem)
+    if (menuItem) {
       menuItem.setAttribute("checked", "true");
+    }
   },
 
-  tempTrustAllKeys: function() {
+  tempTrustAllKeys() {
     this.trustAllKeys = !this.trustAllKeys;
   },
 
   /*
   toggleAttachOwnKey: function() {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.toggleAttachOwnKey\n");
     EnigmailCore.getService(window); // make sure Enigmail is loaded and working
 
@@ -858,18 +967,17 @@ Enigmail.msg = {
     EnigmailCore.getService(window); // make sure Enigmail is loaded and working
 
     this.protectHeaders = !this.protectHeaders;
 
     this.displayProtectHeadersStatus();
   },
   */
 
-  displayProtectHeadersStatus: function() {
-    return;
+  displayProtectHeadersStatus() {
     /*
     let bc = document.getElementById("enigmail-bc-protectHdr");
 
     if (this.protectHeaders) {
       bc.setAttribute("checked", "true");
       bc.setAttribute("tooltiptext", EnigmailLocale.getString("msgCompose.protectSubject.tooltip"));
     }
     else {
@@ -906,135 +1014,153 @@ Enigmail.msg = {
     }
 
     if (attachIcon)
       attachIcon.setAttribute("tooltiptext", this.statusAttachOwnKey);
 
   },
   */
 
-  attachOwnKey: function(id) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.attachOwnKey: " + id + "\n");
+  attachOwnKey(id) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.attachOwnKey: " + id + "\n"
+    );
     console.debug("Enigmail.msg.attachOwnKey " + id);
 
-    if (this.attachOwnKeyObj.attachedKey && (this.attachOwnKeyObj.attachedKey != id)) {
+    if (
+      this.attachOwnKeyObj.attachedKey &&
+      this.attachOwnKeyObj.attachedKey != id
+    ) {
       // remove attached key if user ID changed
       this.removeAttachedKey();
     }
 
     if (!this.attachOwnKeyObj.attachedKey) {
       var attachedObj = this.extractAndAttachKey([id], true);
       if (attachedObj) {
         this.attachOwnKeyObj.attachedObj = attachedObj;
         this.attachOwnKeyObj.attachedKey = id;
       }
     }
   },
 
-  attachKey: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.attachKey: \n");
+  attachKey() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.attachKey: \n"
+    );
 
     var resultObj = {};
     var inputObj = {};
     inputObj.dialogHeader = EnigmailLocale.getString("keysToExport");
     inputObj.options = "multisel,allowexpired,nosending";
     if (this.trustAllKeys) {
       inputObj.options += ",trustallkeys";
     }
-    var userIdValue = "";
-
-    window.openDialog("chrome://openpgp/content/ui/enigmailKeySelection.xhtml", "", "dialog,modal,centerscreen,resizable", inputObj, resultObj);
+    window.openDialog(
+      "chrome://openpgp/content/ui/enigmailKeySelection.xhtml",
+      "",
+      "dialog,modal,centerscreen,resizable",
+      inputObj,
+      resultObj
+    );
     try {
-      if (resultObj.cancelled) return;
+      if (resultObj.cancelled) {
+        return;
+      }
       this.extractAndAttachKey(resultObj.userList, true);
-    }
-    catch (ex) {
+    } catch (ex) {
       // cancel pressed -> do nothing
-      return;
     }
   },
 
-  extractAndAttachKey: function(uid, warnOnError) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.extractAndAttachKey: \n");
+  extractAndAttachKey(uid, warnOnError) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.extractAndAttachKey: \n"
+    );
     var enigmailSvc = EnigmailCore.getService(window);
-    if (!enigmailSvc)
+    if (!enigmailSvc) {
       return null;
+    }
 
     var tmpDir = EnigmailFiles.getTempDir();
     var tmpFile;
     try {
-      tmpFile = Components.classes[LOCAL_FILE_CONTRACTID].createInstance(Components.interfaces.nsIFile);
+      tmpFile = Cc[LOCAL_FILE_CONTRACTID].createInstance(Ci.nsIFile);
       tmpFile.initWithPath(tmpDir);
       if (!(tmpFile.isDirectory() && tmpFile.isWritable())) {
         EnigmailDialog.alert(window, EnigmailLocale.getString("noTempDir"));
         return null;
       }
-    }
-    catch (ex) {
-      EnigmailLog.writeException("enigmailMsgComposeOverlay.js: Enigmail.msg.extractAndAttachKey", ex);
+    } catch (ex) {
+      EnigmailLog.writeException(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.extractAndAttachKey",
+        ex
+      );
     }
     tmpFile.append("key.asc");
-    tmpFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0o600);
+    tmpFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
 
     // save file
     var exitCodeObj = {};
     var errorMsgObj = {};
 
     EnigmailKeyRing.extractKey(false, uid, tmpFile, exitCodeObj, errorMsgObj);
     if (exitCodeObj.value !== 0) {
-      if (warnOnError) EnigmailDialog.alert(window, errorMsgObj.value);
+      if (warnOnError) {
+        EnigmailDialog.alert(window, errorMsgObj.value);
+      }
       return null;
     }
 
     // create attachment
-    var ioServ = Components.classes[IOSERVICE_CONTRACTID].getService(Components.interfaces.nsIIOService);
+    var ioServ = Services.io;
     var tmpFileURI = ioServ.newFileURI(tmpFile);
-    var keyAttachment = Components.classes["@mozilla.org/messengercompose/attachment;1"].createInstance(Components.interfaces.nsIMsgAttachment);
+    var keyAttachment = Cc[
+      "@mozilla.org/messengercompose/attachment;1"
+    ].createInstance(Ci.nsIMsgAttachment);
     keyAttachment.url = tmpFileURI.spec;
-    if ((uid.length == 1) && (uid[0].search(/^(0x)?[a-fA-F0-9]+$/) === 0)) {
+    if (uid.length == 1 && uid[0].search(/^(0x)?[a-fA-F0-9]+$/) === 0) {
       keyAttachment.name = uid[0].substr(-16, 16) + ".asc";
-      if (keyAttachment.name.search(/^0x/) < 0)
+      if (keyAttachment.name.search(/^0x/) < 0) {
         keyAttachment.name = "0x" + keyAttachment.name;
-    }
-    else {
+      }
+    } else {
       keyAttachment.name = "pgpkeys.asc";
     }
     keyAttachment.temporary = true;
     keyAttachment.contentType = "application/pgp-keys";
 
     // add attachment to msg
     this.addAttachment(keyAttachment);
 
     try {
       // TB only
       ChangeAttachmentBucketVisibility(false);
-    }
-    catch (ex) {}
+    } catch (ex) {}
     gContentChanged = true;
     return keyAttachment;
   },
 
-  addAttachment: function(attachment) {
+  addAttachment(attachment) {
     AddAttachments([attachment]);
   },
 
   /*
   enableUndoEncryption: function(newStatus) {
     return;
     let eue = document.getElementById("enigmail_undo_encryption");
 
     if (newStatus) {
       eue.removeAttribute("disabled");
     }
     else
       eue.setAttribute("disabled", "true");
   },
   */
 
-
   /**
    *  undo the encryption or signing; get back the original (unsigned/unencrypted) text
    *
    * useEditorUndo |Number|:   > 0  use undo function of editor |n| times
    *                           0: replace text with original text
    */
   /*
   undoEncryption: function(useEditorUndo) {
@@ -1057,134 +1183,142 @@ Enigmail.msg = {
     }
 
     var node;
     var nodeNumber;
     this.removeAttachedKey();
   },
   */
 
-
-  removeAttachedKey: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.removeAttachedKey: \n");
+  removeAttachedKey() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.removeAttachedKey: \n"
+    );
 
     var bucketList = document.getElementById("attachmentBucket");
     var node = bucketList.firstChild;
 
-    if (bucketList && bucketList.hasChildNodes() && this.attachOwnKeyObj.attachedObj) {
+    if (
+      bucketList &&
+      bucketList.hasChildNodes() &&
+      this.attachOwnKeyObj.attachedObj
+    ) {
       // undo attaching own key
-      var nodeNumber = -1;
       while (node) {
-        ++nodeNumber;
         if (node.attachment.url == this.attachOwnKeyObj.attachedObj.url) {
           node = bucketList.removeChild(node);
           // Let's release the attachment object held by the node else it won't go away until the window is destroyed
           node.attachment = null;
           this.attachOwnKeyObj.attachedObj = null;
           this.attachOwnKeyObj.attachedKey = null;
           node = null; // exit loop
-        }
-        else {
+        } else {
           node = node.nextSibling;
         }
       }
       if (!bucketList.hasChildNodes()) {
         try {
           // TB only
           ChangeAttachmentBucketVisibility(true);
-        }
-        catch (ex) {}
+        } catch (ex) {}
       }
     }
   },
 
-  getSecurityParams: function(compFields = null, doQueryInterface = false) {
+  getSecurityParams(compFields = null, doQueryInterface = false) {
     if (!compFields) {
       compFields = gMsgCompose.compFields;
     }
 
     return compFields.composeSecure;
   },
 
-  setSecurityParams: function(newSecurityParams) {
+  setSecurityParams(newSecurityParams) {
     gMsgCompose.compFields.composeSecure = newSecurityParams;
   },
 
   // Used on send failure, to reset the pre-send modifications
-  resetUpdatedFields: function() {
+  resetUpdatedFields() {
     this.removeAttachedKey();
 
     // reset subject
     let p = Enigmail.msg.getSecurityParams();
     if (EnigmailMimeEncrypt.isEnigmailCompField(p)) {
       let si = p.wrappedJSObject;
       if (si.originalSubject) {
         gMsgCompose.compFields.subject = si.originalSubject;
       }
     }
   },
 
-  replaceEditorText: function(text) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.replaceEditorText:\n");
+  replaceEditorText(text) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.replaceEditorText:\n"
+    );
 
     this.editorSelectAll();
     // Overwrite text in clipboard for security
     // (Otherwise plaintext will be available in the clipbaord)
 
     if (this.editor.textLength > 0) {
       this.editorInsertText("Enigmail");
-    }
-    else {
+    } else {
       this.editorInsertText(" ");
     }
 
     this.editorSelectAll();
     this.editorInsertText(text);
   },
 
-  goAccountManager: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.goAccountManager:\n");
+  goAccountManager() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.goAccountManager:\n"
+    );
     EnigmailCore.getService(window);
     let currentId = null;
     let account = null;
     try {
       currentId = getCurrentIdentity();
       account = EnigmailFuncs.getAccountForIdentity(currentId);
-    }
-    catch (ex) {}
-    window.openDialog("chrome://openpgp/content/ui/editSingleAccount.xhtml", "", "dialog,modal,centerscreen", {
-      identity: currentId,
-      account: account
-    });
+    } catch (ex) {}
+    window.openDialog(
+      "chrome://openpgp/content/ui/editSingleAccount.xhtml",
+      "",
+      "dialog,modal,centerscreen",
+      {
+        identity: currentId,
+        account,
+      }
+    );
     this.setIdentityDefaults();
   },
 
   /**
    * Determine if Enigmail is enabled for the account
    */
 
-  wasEnigmailAddOnInstalled: function() {
-    return (EnigmailPrefs.getPref("configuredVersion") !== "");
+  wasEnigmailAddOnInstalled() {
+    return EnigmailPrefs.getPref("configuredVersion") !== "";
   },
 
-  wasEnigmailEnabledForIdentity: function() {
+  wasEnigmailEnabledForIdentity() {
     return this.identity.getBoolAttribute("enablePgp");
   },
 
   // TODO: should we use a different flag for "PGP is enabled in TB78+"?
   //       or check in combination with identityEnigmailPrefsMigrated?
-  isEnigmailEnabledForIdentity: function() {
+  isEnigmailEnabledForIdentity() {
     //return this.identity.getBoolAttribute("enablePgp");
     return true;
   },
 
   /**
    * Determine if Autocrypt is enabled for the account
    */
-  isAutocryptEnabled: function() {
+  isAutocryptEnabled() {
     return false;
     /*
     if (Enigmail.msg.wasEnigmailEnabledForIdentity()) {
       let srv = this.getCurrentIncomingServer();
       return (srv ? srv.getBoolValue("enableAutocrypt") : false);
     }
 
     return false;
@@ -1235,17 +1369,16 @@ Enigmail.msg = {
         break;
       default:
         this.displaySecuritySettings();
     }
 
   },
   */
 
-
   // changes the DEFAULT sendMode
   // - also called internally for saved emails
   /*
   setSendMode: function(sendMode) {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setSendMode: sendMode=" + sendMode + "\n");
     const SIGN = EnigmailConstants.SEND_SIGNED;
     const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
 
@@ -1266,30 +1399,28 @@ Enigmail.msg = {
     if (!this.sendModeDirty && (this.sendMode != origSendMode) && sendMode != 'sign' && sendMode != 'encrypt') {
       this.sendModeDirty = true;
     }
     this.processFinalState();
     this.updateStatusBar();
   },
   */
 
-
   /**
     key function to process the final encrypt/sign/pgpmime state from all settings
     @param sendFlags: contains the sendFlags if the message is really processed. Optional, can be null
       - uses as INPUT:
          - this.sendMode
          - this.encryptForced, this.encryptSigned
       - uses as OUTPUT:
          - this.statusEncrypt, this.statusSign
 
     no return value
   */
-  processFinalState: function(sendFlags) {
-    return;
+  processFinalState(sendFlags) {
     /*
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.processFinalState()\n");
 
     const SIGN = EnigmailConstants.SEND_SIGNED;
     const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
 
 
     let encReason = "";
@@ -1335,26 +1466,24 @@ Enigmail.msg = {
       try {
         setSecuritySettings("2");
       }
       catch (ex) {}
     }
     */
   },
 
-
   // process icon/strings of status bar buttons and menu entries according to final encrypt/sign/pgpmime status
   // - uses as INPUT:
   //   - this.statusEncrypt, this.statusSign
   // - uses as OUTPUT:
   //   - resulting icon symbols
   //   - this.statusEncryptStr, this.statusSignStr, this.statusPGPMimeStr, this.statusInlinePGPStr, this.statusAttachOwnKey
   //   - this.statusSMimeStr
-  updateStatusBar: function() {
-    return;
+  updateStatusBar() {
     /*
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.updateStatusBar()\n");
 
     if (!this.identity) {
       this.identity = getCurrentIdentity();
     }
 
     var toolbarTxt = document.getElementById("enigmail-toolbar-text");
@@ -1483,17 +1612,16 @@ Enigmail.msg = {
       attachBroadcaster.removeAttribute("disabled");
     }
     else {
       attachBroadcaster.setAttribute("disabled", "true");
     }
     */
   },
 
-
   /*
   displaySMimeToolbar: function() {
     let s = document.getElementById("signing-status");
     let e = document.getElementById("encryption-status");
 
         if (s) s.removeAttribute("collapsed");
         if (e) e.removeAttribute("collapsed");
         if (s) s.setAttribute("collapsed", "true");
@@ -1524,29 +1652,33 @@ Enigmail.msg = {
     }
 
     return allow;
   },
   */
 
   /* check if encryption is possible (have keys for everyone or not)
    */
-  determineSendFlags: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.focusChange: Enigmail.msg.determineSendFlags\n");
+  determineSendFlags() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.focusChange: Enigmail.msg.determineSendFlags\n"
+    );
 
     let detailsObj = {};
 
     if (!this.identity) {
       this.identity = getCurrentIdentity();
     }
 
     var compFields = gMsgCompose.compFields;
 
     if (!Enigmail.msg.composeBodyReady) {
-      compFields = Components.classes["@mozilla.org/messengercompose/composefields;1"].createInstance(Components.interfaces.nsIMsgCompFields);
+      compFields = Cc[
+        "@mozilla.org/messengercompose/composefields;1"
+      ].createInstance(Ci.nsIMsgCompFields);
     }
     Recipients2CompFields(compFields);
     gMsgCompose.expandMailingLists();
 
     if (Enigmail.msg.isEnigmailEnabledForIdentity()) {
       // process list of to/cc email addresses
       // - bcc email addresses are ignored, when processing whether to sign/encrypt
       var toAddrList = [];
@@ -1556,17 +1688,17 @@ Enigmail.msg = {
         recList = compFields.splitRecipients(compFields.to, true, arrLen);
         this.addRecipients(toAddrList, recList);
       }
       if (compFields.cc.length > 0) {
         recList = compFields.splitRecipients(compFields.cc, true, arrLen);
         this.addRecipients(toAddrList, recList);
       }
 
-      let validKeyList = Enigmail.hlp.validKeysForAllRecipients(toAddrList.join(", "), detailsObj);
+      Enigmail.hlp.validKeysForAllRecipients(toAddrList.join(", "), detailsObj);
       //this.autoPgpEncryption = (validKeyList !== null);
     }
 
     // process and signal new resulting state
     //this.processFinalState();
     this.updateStatusBar();
 
     return detailsObj;
@@ -1708,28 +1840,30 @@ Enigmail.msg = {
       this.encryptForced = inputObj.encrypt;
     }
 
     //this.processFinalState();
     this.updateStatusBar();
   },
   */
 
-
-  addRecipients: function(toAddrList, recList) {
+  addRecipients(toAddrList, recList) {
     for (var i = 0; i < recList.length; i++) {
       try {
-        toAddrList.push(EnigmailFuncs.stripEmail(recList[i].replace(/[",]/g, "")));
-      }
-      catch (ex) {}
+        toAddrList.push(
+          EnigmailFuncs.stripEmail(recList[i].replace(/[",]/g, ""))
+        );
+      } catch (ex) {}
     }
   },
 
-  setDraftStatus: function(doEncrypt) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setDraftStatus - enabling draft mode\n");
+  setDraftStatus(doEncrypt) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.setDraftStatus - enabling draft mode\n"
+    );
 
     // TODO: rewrite to properly set draft status using new flags
     /*
     // Draft Status:
     // N (for new style) plus String of 4 numbers:
     // 1: encryption
     // 2: signing
     // 3: PGP/MIME
@@ -1740,122 +1874,136 @@ Enigmail.msg = {
       (gSendEncrypted && !gOptionalEncryption) + 
       (gSendSigned) + 
       (gAttachMyPublicPGPKey ? "1" : "0") + (doEncrypt && this.protectHeaders ? "1" : "0");
 
     this.setAdditionalHeader("X-Enigmail-Draft-Status", draftStatus);
     */
   },
 
-  getForceRecipientDlg: function() {
-    return false;
-  },
-
-  getSenderUserId: function() {
+  getSenderUserId() {
     var userIdValue = null;
 
     if (this.identity.getIntAttribute("pgpKeyMode") > 0) {
       userIdValue = this.identity.getCharAttribute("pgpkeyId");
 
       if (!userIdValue) {
-
         var mesg = EnigmailLocale.getString("composeSpecifyEmail");
 
         var valueObj = {
-          value: userIdValue
+          value: userIdValue,
         };
 
         if (EnigmailDialog.promptValue(window, mesg, valueObj)) {
           userIdValue = valueObj.value;
         }
       }
 
       if (userIdValue) {
         this.identity.setCharAttribute("pgpkeyId", userIdValue);
-
-      }
-      else {
+      } else {
         this.identity.setIntAttribute("pgpKeyMode", 0);
       }
     }
 
-    if (typeof(userIdValue) != "string") {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.getSenderUserId: type of userIdValue=" + typeof(userIdValue) + "\n");
+    if (typeof userIdValue != "string") {
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.getSenderUserId: type of userIdValue=" +
+          typeof userIdValue +
+          "\n"
+      );
       userIdValue = this.identity.email;
     }
 
     if (this.identity.getIntAttribute("pgpKeyMode") === 0) {
       let key = EnigmailKeyRing.getSecretKeyByEmail(userIdValue);
       if (key) {
         userIdValue = "0x" + key.fpr;
       }
     }
     return userIdValue;
   },
 
-
   /* process rules and find keys for passed email addresses
    * This is THE core method to prepare sending encryptes emails.
    * - it processes the recipient rules (if not disabled)
    * - it
    *
    * @sendFlags:    Longint - all current combined/processed send flags (incl. optSendFlags)
    * @optSendFlags: Longint - may only be SEND_ALWAYS_TRUST or SEND_ENCRYPT_TO_SELF
    * @fromAddr:     String - from email
    * @toAddrList:   Array  - both to and cc receivers
    * @bccAddrList:  Array  - bcc receivers
    * @return:       Object:
    *                - sendFlags (Longint)
    *                - toAddrStr  comma separated string of unprocessed to/cc emails
    *                - bccAddrStr comma separated string of unprocessed to/cc emails
    *                or null (cancel sending the email)
    */
-  keySelection: function(enigmailSvc, sendFlags, optSendFlags, fromAddr, toAddrList, bccAddrList) {
+  keySelection(
+    enigmailSvc,
+    sendFlags,
+    optSendFlags,
+    fromAddr,
+    toAddrList,
+    bccAddrList
+  ) {
     EnigmailLog.DEBUG("=====> keySelection()\n");
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection()\n");
-
-    const SIGN = EnigmailConstants.SEND_SIGNED;
-    const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection()\n"
+    );
 
     let toAddrStr = toAddrList.join(", ");
     let bccAddrStr = bccAddrList.join(", ");
     let keyMap = {};
 
     // NOTE: If we only have bcc addresses, we currently do NOT process rules and select keys at all
     //       This is GOOD because sending keys for bcc addresses makes bcc addresses visible
     //       (thus compromising the concept of bcc)
     //       THUS, we disable encryption even though all bcc receivers might want to have it encrypted.
     if (toAddrStr.length === 0) {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection(): skip key selection because we neither have \"to\" nor \"cc\" addresses\n");
-
-        //sendFlags |= EnigmailConstants.SEND_PGP_MIME;
-        //sendFlags &= ~EnigmailConstants.SEND_PGP_MIME;
+      EnigmailLog.DEBUG(
+        'enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection(): skip key selection because we neither have "to" nor "cc" addresses\n'
+      );
+
+      //sendFlags |= EnigmailConstants.SEND_PGP_MIME;
+      //sendFlags &= ~EnigmailConstants.SEND_PGP_MIME;
 
       return {
-        sendFlags: sendFlags,
-        toAddrStr: toAddrStr,
-        bccAddrStr: bccAddrStr,
-        keyMap: keyMap
+        sendFlags,
+        toAddrStr,
+        bccAddrStr,
+        keyMap,
       };
     }
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection(): toAddrStr=\"" + toAddrStr + "\" bccAddrStr=\"" + bccAddrStr + "\"\n");
-
-    var forceRecipientSettings = this.getForceRecipientDlg();
+    EnigmailLog.DEBUG(
+      'enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection(): toAddrStr="' +
+        toAddrStr +
+        '" bccAddrStr="' +
+        bccAddrStr +
+        '"\n'
+    );
 
     // REPEAT 1 or 2 times:
     // NOTE: The only way to call this loop twice is to come to the "continue;" statement below,
     //       which forces a second iteration (with forceRecipientSettings==true)
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection(): return toAddrStr=\"" + toAddrStr + "\" bccAddrStr=\"" + bccAddrStr + "\"\n");
+    EnigmailLog.DEBUG(
+      'enigmailMsgComposeOverlay.js: Enigmail.msg.keySelection(): return toAddrStr="' +
+        toAddrStr +
+        '" bccAddrStr="' +
+        bccAddrStr +
+        '"\n'
+    );
     EnigmailLog.DEBUG("  <=== keySelection()\n");
     return {
-      sendFlags: sendFlags,
-      toAddrStr: toAddrStr,
-      bccAddrStr: bccAddrStr,
-      keyMap: keyMap
+      sendFlags,
+      toAddrStr,
+      bccAddrStr,
+      keyMap,
     };
   },
 
   /**
    * Determine if S/MIME or OpenPGP should be used
    *
    * @param sendFlags: Number - input send flags.
    *
@@ -1883,41 +2031,45 @@ Enigmail.msg = {
         }
       }
     }
 
     return 1;
   },
   */
 
-
   /**
    * check if S/MIME encryption can be enabled
    *
    * @return: Boolean - true: keys for all recipients are available
    */
-  isSmimeEncryptionPossible: function() {
+  isSmimeEncryptionPossible() {
     let id = getCurrentIdentity();
 
-    if (id.getUnicharAttribute("encryption_cert_name") === "") return false;
+    if (id.getUnicharAttribute("encryption_cert_name") === "") {
+      return false;
+    }
 
     // enable encryption if keys for all recipients are available
 
     let missingCount = {};
     let emailAddresses = {};
 
     try {
-      if (!gMsgCompose.compFields.hasRecipients) return false;
-      Components.classes["@mozilla.org/messenger-smime/smimejshelper;1"]
-        .createInstance(Components.interfaces.nsISMimeJSHelper)
-        .getNoCertAddresses(gMsgCompose.compFields,
+      if (!gMsgCompose.compFields.hasRecipients) {
+        return false;
+      }
+      Cc["@mozilla.org/messenger-smime/smimejshelper;1"]
+        .createInstance(Ci.nsISMimeJSHelper)
+        .getNoCertAddresses(
+          gMsgCompose.compFields,
           missingCount,
-          emailAddresses);
-    }
-    catch (e) {
+          emailAddresses
+        );
+    } catch (e) {
       return false;
     }
 
     if (missingCount.value === 0) {
       return true;
     }
 
     return false;
@@ -1925,30 +2077,38 @@ Enigmail.msg = {
 
   /* Manage the wrapping of inline signed mails
    *
    * @wrapresultObj: Result:
    * @wrapresultObj.cancelled, true if send operation is to be cancelled, else false
    * @wrapresultObj.usePpgMime, true if message send option was changed to PGP/MIME, else false
    */
 
-  wrapInLine: function(wrapresultObj) {
+  wrapInLine(wrapresultObj) {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: WrapInLine\n");
     wrapresultObj.cancelled = false;
     wrapresultObj.usePpgMime = false;
     try {
-      const dce = Components.interfaces.nsIDocumentEncoder;
-      var editor = gMsgCompose.editor.QueryInterface(Components.interfaces.nsIEditorMailSupport);
+      const dce = Ci.nsIDocumentEncoder;
+      var editor = gMsgCompose.editor.QueryInterface(Ci.nsIEditorMailSupport);
       var encoderFlags = dce.OutputFormatted | dce.OutputLFLineBreak;
 
       var wrapWidth = this.getMailPref("mailnews.wraplength");
       if (wrapWidth > 0 && wrapWidth < 68 && editor.wrapWidth > 0) {
-        if (EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("minimalLineWrapping", [wrapWidth]))) {
+        if (
+          EnigmailDialog.confirmDlg(
+            window,
+            EnigmailLocale.getString("minimalLineWrapping", [wrapWidth])
+          )
+        ) {
           wrapWidth = 68;
-          EnigmailPrefs.getPrefRoot().setIntPref("mailnews.wraplength", wrapWidth);
+          EnigmailPrefs.getPrefRoot().setIntPref(
+            "mailnews.wraplength",
+            wrapWidth
+          );
         }
       }
 
       if (wrapWidth && editor.wrapWidth > 0) {
         // First use standard editor wrap mechanism:
         editor.wrapWidth = wrapWidth - 2;
         editor.rewrap(true);
         editor.wrapWidth = wrapWidth;
@@ -1964,42 +2124,46 @@ Enigmail.msg = {
         // inspect all lines of mail text to detect if we still have excessive lines which the "standard" editor wrapper leaves
         for (i = 0; i < wrapText.length; i++) {
           if (wrapText[i].length > wrapWidth) {
             excess = 1;
           }
         }
 
         if (excess) {
-          EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Excess lines detected\n");
+          EnigmailLog.DEBUG(
+            "enigmailMsgComposeOverlay.js: Excess lines detected\n"
+          );
           var resultObj = {};
-          window.openDialog("chrome://openpgp/content/ui/enigmailWrapSelection.xhtml", "", "dialog,modal,centerscreen", resultObj);
+          window.openDialog(
+            "chrome://openpgp/content/ui/enigmailWrapSelection.xhtml",
+            "",
+            "dialog,modal,centerscreen",
+            resultObj
+          );
           try {
             if (resultObj.cancelled) {
               // cancel pressed -> do not send, return instead.
               wrapresultObj.cancelled = true;
               return;
             }
-          }
-          catch (ex) {
+          } catch (ex) {
             // cancel pressed -> do not send, return instead.
             wrapresultObj.cancelled = true;
             return;
           }
 
-          var quote = "";
           var limitedLine = "";
           var restOfLine = "";
 
           var WrapSelect = resultObj.Select;
           switch (WrapSelect) {
             case "0": // Selection: Force rewrap
               for (i = 0; i < wrapText.length; i++) {
                 if (wrapText[i].length > wrapWidth) {
-
                   // If the current line is too long, limit it hard to wrapWidth and insert the rest as the next line into wrapText array
                   limitedLine = wrapText[i].slice(0, wrapWidth);
                   restOfLine = wrapText[i].slice(wrapWidth);
 
                   // We should add quotes at the beginning of "restOfLine", if limitedLine is a quoted line
                   // However, this would be purely academic, because limitedLine will always be "standard"-wrapped
                   // by the editor-rewrapper at the space between quote sign (>) and the quoted text.
 
@@ -2016,108 +2180,131 @@ Enigmail.msg = {
               wrapresultObj.cancelled = true;
               return;
           } //switch
         }
         // Now join all lines together again and feed it back into the compose editor.
         var newtext = wrapText.join("\n");
         this.replaceEditorText(newtext);
       }
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: Exception while wrapping=" + ex + "\n"
+      );
     }
-    catch (ex) {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Exception while wrapping=" + ex + "\n");
-    }
-
   },
 
   // Save draft message. We do not want most of the other processing for encrypted mails here...
-  saveDraftMessage: function() {
+  saveDraftMessage() {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: saveDraftMessage()\n");
 
-
-    let doEncrypt = Enigmail.msg.isEnigmailEnabledForIdentity() && this.identity.getBoolAttribute("autoEncryptDrafts");
+    let doEncrypt =
+      Enigmail.msg.isEnigmailEnabledForIdentity() &&
+      this.identity.getBoolAttribute("autoEncryptDrafts");
 
     this.setDraftStatus(doEncrypt);
 
     if (!doEncrypt) {
       EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: drafts disabled\n");
 
       try {
         let p = Enigmail.msg.getSecurityParams();
         if (EnigmailMimeEncrypt.isEnigmailCompField(p)) {
           p.wrappedJSObject.sendFlags = 0;
         }
-      }
-      catch (ex) {}
+      } catch (ex) {}
 
       return true;
     }
 
-    let sendFlags = EnigmailConstants.SEND_PGP_MIME | EnigmailConstants.SEND_ENCRYPTED | EnigmailConstants.SAVE_MESSAGE | EnigmailConstants.SEND_ALWAYS_TRUST;
+    let sendFlags =
+      EnigmailConstants.SEND_PGP_MIME |
+      EnigmailConstants.SEND_ENCRYPTED |
+      EnigmailConstants.SAVE_MESSAGE |
+      EnigmailConstants.SEND_ALWAYS_TRUST;
 
     if (this.protectHeaders) {
       sendFlags |= EnigmailConstants.ENCRYPT_HEADERS;
     }
 
     let fromAddr = this.identity.email;
     let userIdValue = this.getSenderUserId();
     if (userIdValue) {
       fromAddr = userIdValue;
     }
 
     let enigmailSvc = EnigmailCore.getService(window);
-    if (!enigmailSvc) return true;
+    if (!enigmailSvc) {
+      return true;
+    }
 
     //if (this.preferPgpOverSmime(sendFlags) === 0) return true; // use S/MIME
 
     // Try to save draft
 
-    var testCipher = null;
     var testExitCodeObj = {};
     var testStatusFlagsObj = {};
     var testErrorMsgObj = {};
 
     // encrypt test message for test recipients
     var testPlain = "Test Message";
     var testUiFlags = EnigmailConstants.UI_TEST;
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.saveDraft(): call encryptMessage() for fromAddr=\"" + fromAddr + "\"\n");
-    testCipher = EnigmailEncryption.encryptMessage(null, testUiFlags, testPlain,
-      fromAddr, fromAddr, "",
+    EnigmailLog.DEBUG(
+      'enigmailMsgComposeOverlay.js: Enigmail.msg.saveDraft(): call encryptMessage() for fromAddr="' +
+        fromAddr +
+        '"\n'
+    );
+    EnigmailEncryption.encryptMessage(
+      null,
+      testUiFlags,
+      testPlain,
+      fromAddr,
+      fromAddr,
+      "",
       sendFlags | EnigmailConstants.SEND_TEST,
       testExitCodeObj,
       testStatusFlagsObj,
-      testErrorMsgObj);
-
-    if (testStatusFlagsObj.value & (EnigmailConstants.INVALID_RECIPIENT | EnigmailConstants.NO_SECKEY)) {
+      testErrorMsgObj
+    );
+
+    if (
+      testStatusFlagsObj.value &
+      (EnigmailConstants.INVALID_RECIPIENT | EnigmailConstants.NO_SECKEY)
+    ) {
       // check if own key is invalid
       if (testErrorMsgObj.value && testErrorMsgObj.value.length > 0) {
         ++this.saveDraftError;
         if (this.saveDraftError === 1) {
-          this.notifyUser(3, EnigmailLocale.getString("msgCompose.cannotSaveDraft"), "saveDraftFailed",
-            testErrorMsgObj.value);
+          this.notifyUser(
+            3,
+            EnigmailLocale.getString("msgCompose.cannotSaveDraft"),
+            "saveDraftFailed",
+            testErrorMsgObj.value
+          );
         }
         return false;
       }
     }
 
     let secInfo;
 
     let param = Enigmail.msg.getSecurityParams();
     if (EnigmailMimeEncrypt.isEnigmailCompField(param)) {
       secInfo = param.wrappedJSObject;
-    }
-    else {
+    } else {
       try {
         secInfo = EnigmailMimeEncrypt.createMimeEncrypt(param);
         if (secInfo) {
           Enigmail.msg.setSecurityParams(secInfo);
         }
-      }
-      catch (ex) {
-        EnigmailLog.writeException("enigmailMsgComposeOverlay.js: Enigmail.msg.saveDraftMessage", ex);
+      } catch (ex) {
+        EnigmailLog.writeException(
+          "enigmailMsgComposeOverlay.js: Enigmail.msg.saveDraftMessage",
+          ex
+        );
         return false;
       }
     }
 
     secInfo.sendFlags = sendFlags;
     secInfo.UIFlags = 0;
     secInfo.senderEmailAddr = fromAddr;
     secInfo.recipients = fromAddr;
@@ -2127,64 +2314,77 @@ Enigmail.msg = {
 
     if (this.protectHeaders) {
       gMsgCompose.compFields.subject = "";
     }
 
     return true;
   },
 
-  createEnigmailSecurityFields: function(oldSecurityInfo) {
-    let newSecurityInfo = EnigmailMimeEncrypt.createMimeEncrypt(Enigmail.msg.getSecurityParams());
-
-    if (!newSecurityInfo)
-      throw Components.results.NS_ERROR_FAILURE;
+  createEnigmailSecurityFields(oldSecurityInfo) {
+    let newSecurityInfo = EnigmailMimeEncrypt.createMimeEncrypt(
+      Enigmail.msg.getSecurityParams()
+    );
+
+    if (!newSecurityInfo) {
+      throw Cr.NS_ERROR_FAILURE;
+    }
 
     Enigmail.msg.setSecurityParams(newSecurityInfo);
   },
 
-  compileFromAndTo: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.compileFromAndTo\n");
+  compileFromAndTo() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.compileFromAndTo\n"
+    );
     let compFields = gMsgCompose.compFields;
     let toAddrList = [];
-    let recList;
-    let arrLen = {};
 
     if (!Enigmail.msg.composeBodyReady) {
-      compFields = Components.classes["@mozilla.org/messengercompose/composefields;1"].createInstance(Components.interfaces.nsIMsgCompFields);
+      compFields = Cc[
+        "@mozilla.org/messengercompose/composefields;1"
+      ].createInstance(Ci.nsIMsgCompFields);
     }
     Recipients2CompFields(compFields);
     gMsgCompose.expandMailingLists();
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: to='" + compFields.to + "'\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: to='" + compFields.to + "'\n"
+    );
     if (compFields.to.length > 0) {
       toAddrList = EnigmailFuncs.parseEmails(compFields.to, false);
     }
 
     if (compFields.cc.length > 0) {
-      toAddrList = toAddrList.concat(EnigmailFuncs.parseEmails(compFields.cc, false));
+      toAddrList = toAddrList.concat(
+        EnigmailFuncs.parseEmails(compFields.cc, false)
+      );
     }
 
     if (compFields.bcc.length > 0) {
-      toAddrList = toAddrList.concat(EnigmailFuncs.parseEmails(compFields.bcc, false));
+      toAddrList = toAddrList.concat(
+        EnigmailFuncs.parseEmails(compFields.bcc, false)
+      );
     }
 
     for (let addr of toAddrList) {
       // determine incomplete addresses --> do not attempt pEp encryption
-      if (addr.email.search(/.@./) < 0) return null;
+      if (addr.email.search(/.@./) < 0) {
+        return null;
+      }
     }
 
     this.identity = getCurrentIdentity();
     let from = {
       email: this.identity.email,
-      name: this.identity.fullName
+      name: this.identity.fullName,
     };
     return {
-      from: from,
-      toAddrList: toAddrList
+      from,
+      toAddrList,
     };
   },
 
   /*
   sendSmimeEncrypted: function(msgSendType, sendFlags, isOffline) {
     let recList;
     let toAddrList = [];
     let arrLen = {};
@@ -2236,116 +2436,133 @@ Enigmail.msg = {
           }
       }
     }
 
     return true;
   },
   */
 
-  getEncryptionFlags: function(msgSendType) {
+  getEncryptionFlags(msgSendType) {
     let f = 0;
 
-    console.debug(`in getEncryptionFlags, gSendEncrypted=${gSendEncrypted}, gSendSigned=${gSendSigned}`);
-    
+    console.debug(
+      `in getEncryptionFlags, gSendEncrypted=${gSendEncrypted}, gSendSigned=${gSendSigned}`
+    );
+
     if (gSendEncrypted) {
       f |= EnigmailConstants.SEND_ENCRYPTED;
     } else {
       f &= ~EnigmailConstants.SEND_ENCRYPTED;
     }
-    
+
     if (gSendSigned) {
       f |= EnigmailConstants.SEND_SIGNED;
     } else {
       f &= ~EnigmailConstants.SEND_SIGNED;
     }
 
     return f;
   },
 
-  resetDirty: function() {
+  resetDirty() {
     let newSecurityInfo = null;
 
     if (this.dirty) {
       // make sure the sendFlags are reset before the message is processed
       // (it may have been set by a previously cancelled send operation!)
 
       let si = Enigmail.msg.getSecurityParams();
 
       if (EnigmailMimeEncrypt.isEnigmailCompField(si)) {
         si.sendFlags = 0;
         si.originalSubject = gMsgCompose.compFields.subject;
-      }
-      else {
+      } else {
         try {
           newSecurityInfo = EnigmailMimeEncrypt.createMimeEncrypt(si);
           if (newSecurityInfo) {
             newSecurityInfo.sendFlags = 0;
             newSecurityInfo.originalSubject = gMsgCompose.compFields.subject;
 
             Enigmail.msg.setSecurityParams(newSecurityInfo);
           }
-        }
-        catch (ex) {
-          EnigmailLog.writeException("enigmailMsgComposeOverlay.js: Enigmail.msg.resetDirty", ex);
+        } catch (ex) {
+          EnigmailLog.writeException(
+            "enigmailMsgComposeOverlay.js: Enigmail.msg.resetDirty",
+            ex
+          );
         }
       }
     }
 
     return newSecurityInfo;
   },
 
-  determineMsgRecipients: function(sendFlags) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: currentId=" + this.identity +
-      ", " + this.identity.email + "\n");
+  determineMsgRecipients(sendFlags) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: currentId=" +
+        this.identity +
+        ", " +
+        this.identity.email +
+        "\n"
+    );
 
     let promptSvc = EnigmailDialog.getPromptSvc();
     let fromAddr = this.identity.email;
     let toAddrList = [];
     let recList;
     let bccAddrList = [];
     let arrLen = {};
     let splitRecipients;
 
-    if (!Enigmail.msg.isEnigmailEnabledForIdentity()) return true;
+    if (!Enigmail.msg.isEnigmailEnabledForIdentity()) {
+      return true;
+    }
 
     let optSendFlags = 0;
     let msgCompFields = gMsgCompose.compFields;
     let newsgroups = msgCompFields.newsgroups;
 
     // request or preference to always accept (even non-authenticated) keys?
     if (this.trustAllKeys) {
       optSendFlags |= EnigmailConstants.SEND_ALWAYS_TRUST;
-    }
-    else {
+    } else {
       let acceptedKeys = EnigmailPrefs.getPref("acceptedKeys");
       switch (acceptedKeys) {
         case 0: // accept valid/authenticated keys only
           break;
         case 1: // accept all but revoked/disabled/expired keys
           optSendFlags |= EnigmailConstants.SEND_ALWAYS_TRUST;
           break;
         default:
-          EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: INVALID VALUE for acceptedKeys: \"" + acceptedKeys + "\"\n");
+          EnigmailLog.DEBUG(
+            'enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: INVALID VALUE for acceptedKeys: "' +
+              acceptedKeys +
+              '"\n'
+          );
           break;
       }
     }
 
     if (EnigmailPrefs.getPref("encryptToSelf")) {
       optSendFlags |= EnigmailConstants.SEND_ENCRYPT_TO_SELF;
     }
 
     sendFlags |= optSendFlags;
 
     var userIdValue = this.getSenderUserId();
     if (userIdValue) {
       fromAddr = userIdValue;
     }
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients:gMsgCompose=" + gMsgCompose + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients:gMsgCompose=" +
+        gMsgCompose +
+        "\n"
+    );
 
     splitRecipients = msgCompFields.splitRecipients;
 
     if (msgCompFields.to.length > 0) {
       recList = splitRecipients(msgCompFields.to, true, arrLen);
       this.addRecipients(toAddrList, recList);
     }
 
@@ -2358,44 +2575,51 @@ Enigmail.msg = {
     // - note: bcc and encryption is a problem
     // - but bcc to the sender is fine
     if (msgCompFields.bcc.length > 0) {
       recList = splitRecipients(msgCompFields.bcc, true, arrLen);
 
       var bccLC = "";
       try {
         bccLC = EnigmailFuncs.stripEmail(msgCompFields.bcc).toLowerCase();
-      }
-      catch (ex) {}
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: BCC: " + bccLC + "\n");
-
-      var selfBCC = this.identity.email && (this.identity.email.toLowerCase() == bccLC);
+      } catch (ex) {}
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: BCC: " +
+          bccLC +
+          "\n"
+      );
+
+      var selfBCC =
+        this.identity.email && this.identity.email.toLowerCase() == bccLC;
 
       if (selfBCC) {
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: Self BCC\n");
+        EnigmailLog.DEBUG(
+          "enigmailMsgComposeOverlay.js: Enigmail.msg.determineMsgRecipients: Self BCC\n"
+        );
         this.addRecipients(toAddrList, recList);
-
-      }
-      else if (sendFlags & EnigmailConstants.SEND_ENCRYPTED) {
+      } else if (sendFlags & EnigmailConstants.SEND_ENCRYPTED) {
         // BCC and encryption
 
         var dummy = {
-          value: null
+          value: null,
         };
 
-        var hideBccUsers = promptSvc.confirmEx(window,
+        var hideBccUsers = promptSvc.confirmEx(
+          window,
           EnigmailLocale.getString("enigConfirm"),
-          EnigmailLocale.getString("sendingHiddenRcpt"), (promptSvc.BUTTON_TITLE_IS_STRING * promptSvc.BUTTON_POS_0) +
-          (promptSvc.BUTTON_TITLE_CANCEL * promptSvc.BUTTON_POS_1) +
-          (promptSvc.BUTTON_TITLE_IS_STRING * promptSvc.BUTTON_POS_2),
+          EnigmailLocale.getString("sendingHiddenRcpt"),
+          promptSvc.BUTTON_TITLE_IS_STRING * promptSvc.BUTTON_POS_0 +
+            promptSvc.BUTTON_TITLE_CANCEL * promptSvc.BUTTON_POS_1 +
+            promptSvc.BUTTON_TITLE_IS_STRING * promptSvc.BUTTON_POS_2,
           EnigmailLocale.getString("sendWithShownBcc"),
           null,
           EnigmailLocale.getString("sendWithHiddenBcc"),
           null,
-          dummy);
+          dummy
+        );
         switch (hideBccUsers) {
           case 2:
             this.addRecipients(bccAddrList, recList);
             this.addRecipients(toAddrList, recList);
             break;
           case 0:
             this.addRecipients(toAddrList, recList);
             break;
@@ -2407,59 +2631,71 @@ Enigmail.msg = {
 
     if (newsgroups) {
       toAddrList.push(newsgroups);
 
       if (sendFlags & EnigmailConstants.SEND_ENCRYPTED) {
         if (!EnigmailPrefs.getPref("encryptToNews")) {
           EnigmailDialog.alert(window, EnigmailLocale.getString("sendingNews"));
           return false;
-        }
-        else if (!EnigmailDialog.confirmPref(window,
+        } else if (
+          !EnigmailDialog.confirmPref(
+            window,
             EnigmailLocale.getString("sendToNewsWarning"),
             "warnOnSendingNewsgroups",
-            EnigmailLocale.getString("msgCompose.button.send"))) {
+            EnigmailLocale.getString("msgCompose.button.send")
+          )
+        ) {
           return false;
         }
       }
     }
 
     return {
-      sendFlags: sendFlags,
-      optSendFlags: optSendFlags,
-      fromAddr: fromAddr,
-      toAddrList: toAddrList,
-      bccAddrList: bccAddrList
+      sendFlags,
+      optSendFlags,
+      fromAddr,
+      toAddrList,
+      bccAddrList,
     };
   },
 
-  prepareSending: function(sendFlags, toAddrStr, gpgKeys, isOffline) {
+  prepareSending(sendFlags, toAddrStr, gpgKeys, isOffline) {
     // perform confirmation dialog if necessary/requested
-    if ((sendFlags & EnigmailConstants.SEND_WITH_CHECK) &&
-        !this.messageSendCheck()) {
+    if (
+      sendFlags & EnigmailConstants.SEND_WITH_CHECK &&
+      !this.messageSendCheck()
+    ) {
       // Abort send
       if (this.processed) {
         //this.undoEncryption(0);
-      }
-      else {
+      } else {
         this.removeAttachedKey();
       }
 
       return false;
     }
 
     return true;
   },
 
-  prepareSecurityInfo: function(sendFlags, uiFlags, rcpt, newSecurityInfo, keyMap = {}) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.prepareSecurityInfo(): Using PGP/MIME, flags=" + sendFlags + "\n");
+  prepareSecurityInfo(sendFlags, uiFlags, rcpt, newSecurityInfo, keyMap = {}) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.prepareSecurityInfo(): Using PGP/MIME, flags=" +
+        sendFlags +
+        "\n"
+    );
 
     let oldSecurityInfo = Enigmail.msg.getSecurityParams();
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.prepareSecurityInfo: oldSecurityInfo = " + oldSecurityInfo + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.prepareSecurityInfo: oldSecurityInfo = " +
+        oldSecurityInfo +
+        "\n"
+    );
 
     if (!newSecurityInfo) {
       this.createEnigmailSecurityFields(Enigmail.msg.getSecurityParams());
       newSecurityInfo = Enigmail.msg.getSecurityParams().wrappedJSObject;
     }
 
     newSecurityInfo.originalSubject = gMsgCompose.compFields.subject;
     newSecurityInfo.originalReferences = gMsgCompose.compFields.references;
@@ -2469,69 +2705,78 @@ Enigmail.msg = {
 
       if (sendFlags & EnigmailConstants.SEND_ENCRYPTED) {
         gMsgCompose.compFields.subject = "";
 
         if (EnigmailPrefs.getPref("protectReferencesHdr")) {
           gMsgCompose.compFields.references = "";
         }
       }
-
     }
 
     newSecurityInfo.sendFlags = sendFlags;
     newSecurityInfo.UIFlags = uiFlags;
     newSecurityInfo.senderEmailAddr = rcpt.fromAddr;
     newSecurityInfo.bccRecipients = rcpt.bccAddrStr;
     newSecurityInfo.keyMap = keyMap;
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.prepareSecurityInfo: securityInfo = " + newSecurityInfo + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.prepareSecurityInfo: securityInfo = " +
+        newSecurityInfo +
+        "\n"
+    );
     return newSecurityInfo;
   },
 
-  encryptMsg: function(msgSendType) {
+  encryptMsg(msgSendType) {
     // msgSendType: value from nsIMsgCompDeliverMode
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: msgSendType=" + msgSendType + ", gSendSigned=" + gSendSigned + ", gSendEncrypted=" +
-      gSendEncrypted +
-      "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: msgSendType=" +
+        msgSendType +
+        ", gSendSigned=" +
+        gSendSigned +
+        ", gSendEncrypted=" +
+        gSendEncrypted +
+        "\n"
+    );
 
     const SIGN = EnigmailConstants.SEND_SIGNED;
     const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
-    const DeliverMode = Components.interfaces.nsIMsgCompDeliverMode;
-    let promptSvc = EnigmailDialog.getPromptSvc();
-
-    var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
+    const DeliverMode = Ci.nsIMsgCompDeliverMode;
+
+    var ioService = Services.io;
     // EnigSend: Handle both plain and encrypted messages below
-    var isOffline = (ioService && ioService.offline);
+    var isOffline = ioService && ioService.offline;
 
     let sendFlags = this.getEncryptionFlags(msgSendType);
 
-    // if smime
-    {
-      //return this.sendSmimeEncrypted(msgSendType, sendFlags, isOffline);
-    }
-
     switch (msgSendType) {
       case DeliverMode.SaveAsDraft:
       case DeliverMode.SaveAsTemplate:
       case DeliverMode.AutoSaveAsDraft:
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: detected save draft\n");
+        EnigmailLog.DEBUG(
+          "enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: detected save draft\n"
+        );
 
         // saving drafts is simpler and works differently than the rest of Enigmail.
         // All rules except account-settings are ignored.
         return this.saveDraftMessage();
     }
 
     this.unsetAdditionalHeader("x-enigmail-draft-status");
 
     let msgCompFields = gMsgCompose.compFields;
     let newsgroups = msgCompFields.newsgroups; // Check if sending to any newsgroups
 
-    if (msgCompFields.to === "" && msgCompFields.cc === "" &&
-      msgCompFields.bcc === "" && newsgroups === "") {
+    if (
+      msgCompFields.to === "" &&
+      msgCompFields.cc === "" &&
+      msgCompFields.bcc === "" &&
+      newsgroups === ""
+    ) {
       // don't attempt to send message if no recipient specified
       var bundle = document.getElementById("bundle_composeMsgs");
       EnigmailDialog.alert(window, bundle.getString("12511"));
       return false;
     }
 
     this.identity = getCurrentIdentity();
 
@@ -2541,42 +2786,54 @@ Enigmail.msg = {
     }
 
     let newSecurityInfo = this.resetDirty();
     this.dirty = 1;
 
     let enigmailSvc = EnigmailCore.getService(window);
     if (!enigmailSvc) {
       var msg = EnigmailLocale.getString("sendUnencrypted");
-      if (EnigmailCore.getEnigmailService() && EnigmailCore.getEnigmailService().initializationError) {
-        msg = EnigmailCore.getEnigmailService().initializationError + "\n\n" + msg;
+      if (
+        EnigmailCore.getEnigmailService() &&
+        EnigmailCore.getEnigmailService().initializationError
+      ) {
+        msg =
+          EnigmailCore.getEnigmailService().initializationError + "\n\n" + msg;
       }
 
-      return EnigmailDialog.confirmDlg(window, msg, EnigmailLocale.getString("msgCompose.button.send"));
+      return EnigmailDialog.confirmDlg(
+        window,
+        msg,
+        EnigmailLocale.getString("msgCompose.button.send")
+      );
     }
 
     try {
       this.modifiedAttach = null;
 
       // fill fromAddr, toAddrList, bcc etc
       let rcpt = this.determineMsgRecipients(sendFlags);
-      if (typeof(rcpt) === "boolean") {
+      if (typeof rcpt === "boolean") {
         return rcpt;
       }
       sendFlags = rcpt.sendFlags;
 
       if (this.sendPgpMime) {
         // Use PGP/MIME
         sendFlags |= EnigmailConstants.SEND_PGP_MIME;
       }
 
-      let result = this.keySelection(enigmailSvc,
+      let result = this.keySelection(
+        enigmailSvc,
         sendFlags, // all current combined/processed send flags (incl. optSendFlags)
         rcpt.optSendFlags, // may only be SEND_ALWAYS_TRUST or SEND_ENCRYPT_TO_SELF
-        rcpt.fromAddr, rcpt.toAddrList, rcpt.bccAddrList);
+        rcpt.fromAddr,
+        rcpt.toAddrList,
+        rcpt.bccAddrList
+      );
       if (!result) {
         return false;
       }
 
       sendFlags = result.sendFlags;
       let toAddrStr = result.toAddrStr;
       let bccAddrStr = result.bccAddrStr;
       let keyMap = result.keyMap;
@@ -2589,27 +2846,33 @@ Enigmail.msg = {
       if (this.preferPgpOverSmime(sendFlags) === 0) {
         // use S/MIME
         Attachments2CompFields(gMsgCompose.compFields); // update list of attachments
         sendFlags = 0;
         return true;
       }
       */
 
-      var usingPGPMime = (sendFlags & EnigmailConstants.SEND_PGP_MIME) &&
-        (sendFlags & (ENCRYPT | SIGN));
+      var usingPGPMime =
+        sendFlags & EnigmailConstants.SEND_PGP_MIME &&
+        sendFlags & (ENCRYPT | SIGN);
 
       if (!this.checkProtectHeaders(sendFlags)) {
         return false;
       }
 
       // ----------------------- Rewrapping code, taken from function "encryptInline"
 
       // Check wrapping, if sign only and inline and plaintext
-      if ((sendFlags & SIGN) && !(sendFlags & ENCRYPT) && !(usingPGPMime) && !(gMsgCompose.composeHTML)) {
+      if (
+        sendFlags & SIGN &&
+        !(sendFlags & ENCRYPT) &&
+        !usingPGPMime &&
+        !gMsgCompose.composeHTML
+      ) {
         var wrapresultObj = {};
 
         this.wrapInLine(wrapresultObj);
 
         if (wrapresultObj.usePpgMime) {
           sendFlags |= EnigmailConstants.SEND_PGP_MIME;
           usingPGPMime = EnigmailConstants.SEND_PGP_MIME;
         }
@@ -2619,196 +2882,249 @@ Enigmail.msg = {
       }
 
       var uiFlags = EnigmailConstants.UI_INTERACTIVE;
 
       if (usingPGPMime) {
         uiFlags |= EnigmailConstants.UI_PGP_MIME;
       }
 
-      if ((sendFlags & (ENCRYPT | SIGN)) && usingPGPMime) {
+      if (sendFlags & (ENCRYPT | SIGN) && usingPGPMime) {
         // Use PGP/MIME
-        newSecurityInfo = this.prepareSecurityInfo(sendFlags, uiFlags, rcpt, newSecurityInfo, keyMap);
+        newSecurityInfo = this.prepareSecurityInfo(
+          sendFlags,
+          uiFlags,
+          rcpt,
+          newSecurityInfo,
+          keyMap
+        );
         newSecurityInfo.recipients = toAddrStr;
         newSecurityInfo.bccRecipients = bccAddrStr;
-      }
-      else if (!this.processed && (sendFlags & (ENCRYPT | SIGN))) {
+      } else if (!this.processed && sendFlags & (ENCRYPT | SIGN)) {
         // use inline PGP
 
         let sendInfo = {
-          sendFlags: sendFlags,
+          sendFlags,
           fromAddr: rcpt.fromAddr,
           toAddr: toAddrStr,
           bccAddr: bccAddrStr,
-          uiFlags: uiFlags,
-          bucketList: document.getElementById("attachmentBucket")
+          uiFlags,
+          bucketList: document.getElementById("attachmentBucket"),
         };
 
         if (!this.encryptInline(sendInfo)) {
           return false;
         }
       }
 
       // update the list of attachments
       Attachments2CompFields(msgCompFields);
 
-      if (!this.prepareSending(sendFlags,
+      if (
+        !this.prepareSending(
+          sendFlags,
           rcpt.toAddrList.join(", "),
           toAddrStr + ", " + bccAddrStr,
           isOffline
-        )) {
-          return false;
+        )
+      ) {
+        return false;
       }
 
       if (msgCompFields.characterSet != "ISO-2022-JP") {
-        if ((usingPGPMime &&
-            ((sendFlags & (ENCRYPT | SIGN)))) || ((!usingPGPMime) && (sendFlags & ENCRYPT))) {
+        if (
+          (usingPGPMime && sendFlags & (ENCRYPT | SIGN)) ||
+          (!usingPGPMime && sendFlags & ENCRYPT)
+        ) {
           try {
             // make sure plaintext is not changed to 7bit
-            if (typeof(msgCompFields.forceMsgEncoding) == "boolean") {
+            if (typeof msgCompFields.forceMsgEncoding == "boolean") {
               msgCompFields.forceMsgEncoding = true;
-              EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: enabled forceMsgEncoding\n");
+              EnigmailLog.DEBUG(
+                "enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: enabled forceMsgEncoding\n"
+              );
             }
-          }
-          catch (ex) {
-            console.debug(ex)
+          } catch (ex) {
+            console.debug(ex);
           }
         }
       }
-    }
-    catch (ex) {
-      EnigmailLog.writeException("enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg", ex);
+    } catch (ex) {
+      EnigmailLog.writeException(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg",
+        ex
+      );
       let msg = EnigmailLocale.getString("signFailed");
-      if (EnigmailCore.getEnigmailService() && EnigmailCore.getEnigmailService().initializationError) {
+      if (
+        EnigmailCore.getEnigmailService() &&
+        EnigmailCore.getEnigmailService().initializationError
+      ) {
         msg += "\n" + EnigmailCore.getEnigmailService().initializationError;
       }
-      return EnigmailDialog.confirmDlg(window, msg, EnigmailLocale.getString("msgCompose.button.sendUnencrypted"));
+      return EnigmailDialog.confirmDlg(
+        window,
+        msg,
+        EnigmailLocale.getString("msgCompose.button.sendUnencrypted")
+      );
     }
 
     // The encryption process for PGP/MIME messages follows "here". It's
     // called automatically from nsMsgCompose->sendMsg().
     // registration for this is done in core.jsm: startup()
 
     return true;
   },
 
-  checkProtectHeaders: function(sendFlags) {
-    if (!(sendFlags & EnigmailConstants.SEND_PGP_MIME)) return true;
+  checkProtectHeaders(sendFlags) {
+    if (!(sendFlags & EnigmailConstants.SEND_PGP_MIME)) {
+      return true;
+    }
     if (sendFlags & EnigmailConstants.SEND_ENCRYPTED) {
-
-      if ((!this.protectHeaders) && EnigmailPrefs.getPref("protectedHeaders") === 1) {
+      if (
+        !this.protectHeaders &&
+        EnigmailPrefs.getPref("protectedHeaders") === 1
+      ) {
         let enableProtection = EnigmailDialog.msgBox(window, {
-          dialogTitle: EnigmailLocale.getString("msgCompose.protectSubject.dialogTitle"),
-          msgtext: EnigmailLocale.getString("msgCompose.protectSubject.question"),
+          dialogTitle: EnigmailLocale.getString(
+            "msgCompose.protectSubject.dialogTitle"
+          ),
+          msgtext: EnigmailLocale.getString(
+            "msgCompose.protectSubject.question"
+          ),
           iconType: EnigmailConstants.ICONTYPE_QUESTION,
-          button1: EnigmailLocale.getString("msgCompose.protectSubject.yesButton"),
-          button2: "extra1:" + EnigmailLocale.getString("msgCompose.protectSubject.noButton")
+          button1: EnigmailLocale.getString(
+            "msgCompose.protectSubject.yesButton"
+          ),
+          button2:
+            "extra1:" +
+            EnigmailLocale.getString("msgCompose.protectSubject.noButton"),
         });
 
-        if (enableProtection === -1) return false;
-
-        EnigmailPrefs.setPref("protectedHeaders", enableProtection === 0 ? 2 : 0);
-        this.protectHeaders = (enableProtection === 0);
+        if (enableProtection === -1) {
+          return false;
+        }
+
+        EnigmailPrefs.setPref(
+          "protectedHeaders",
+          enableProtection === 0 ? 2 : 0
+        );
+        this.protectHeaders = enableProtection === 0;
         this.displayProtectHeadersStatus();
       }
     }
 
     return true;
   },
 
-  encryptInline: function(sendInfo) {
+  encryptInline(sendInfo) {
     // sign/encrypt message using inline-PGP
 
-    const dce = Components.interfaces.nsIDocumentEncoder;
+    const dce = Ci.nsIDocumentEncoder;
     const SIGN = EnigmailConstants.SEND_SIGNED;
     const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
 
     var enigmailSvc = EnigmailCore.getService(window);
-    if (!enigmailSvc) return false;
+    if (!enigmailSvc) {
+      return false;
+    }
 
     if (gMsgCompose.composeHTML) {
       var errMsg = EnigmailLocale.getString("hasHTML");
       EnigmailDialog.alertCount(window, "composeHtmlAlertCount", errMsg);
     }
 
     try {
       var convert = DetermineConvertibility();
-      if (convert == Components.interfaces.nsIMsgCompConvertible.No) {
-        if (!EnigmailDialog.confirmDlg(window,
+      if (convert == Ci.nsIMsgCompConvertible.No) {
+        if (
+          !EnigmailDialog.confirmDlg(
+            window,
             EnigmailLocale.getString("strippingHTML"),
-            EnigmailLocale.getString("msgCompose.button.sendAnyway"))) {
+            EnigmailLocale.getString("msgCompose.button.sendAnyway")
+          )
+        ) {
           return false;
         }
       }
-    }
-    catch (ex) {
-      EnigmailLog.writeException("enigmailMsgComposeOverlay.js: Enigmail.msg.encryptInline", ex);
+    } catch (ex) {
+      EnigmailLog.writeException(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.encryptInline",
+        ex
+      );
     }
 
     try {
       if (this.getMailPref("mail.strictly_mime")) {
-        if (EnigmailDialog.confirmPref(window,
-            EnigmailLocale.getString("quotedPrintableWarn"), "quotedPrintableWarn")) {
+        if (
+          EnigmailDialog.confirmPref(
+            window,
+            EnigmailLocale.getString("quotedPrintableWarn"),
+            "quotedPrintableWarn"
+          )
+        ) {
           EnigmailPrefs.getPrefRoot().setBoolPref("mail.strictly_mime", false);
         }
       }
-    }
-    catch (ex) {}
-
+    } catch (ex) {}
 
     var sendFlowed;
     try {
       sendFlowed = this.getMailPref("mailnews.send_plaintext_flowed");
-    }
-    catch (ex) {
+    } catch (ex) {
       sendFlowed = true;
     }
     var encoderFlags = dce.OutputFormatted | dce.OutputLFLineBreak;
 
-    var editor = gMsgCompose.editor.QueryInterface(Components.interfaces.nsIEditorMailSupport);
+    var editor = gMsgCompose.editor.QueryInterface(Ci.nsIEditorMailSupport);
     var wrapWidth = 72;
 
     if (!(sendInfo.sendFlags & ENCRYPT)) {
       // signed messages only
       if (gMsgCompose.composeHTML) {
         // enforce line wrapping here
         // otherwise the message isn't signed correctly
         try {
           wrapWidth = this.getMailPref("editor.htmlWrapColumn");
 
           if (wrapWidth > 0 && wrapWidth < 68 && gMsgCompose.wrapLength > 0) {
-            if (EnigmailDialog.confirmDlg(window, EnigmailLocale.getString("minimalLineWrapping", [wrapWidth]))) {
-              EnigmailPrefs.getPrefRoot().setIntPref("editor.htmlWrapColumn", 68);
+            if (
+              EnigmailDialog.confirmDlg(
+                window,
+                EnigmailLocale.getString("minimalLineWrapping", [wrapWidth])
+              )
+            ) {
+              EnigmailPrefs.getPrefRoot().setIntPref(
+                "editor.htmlWrapColumn",
+                68
+              );
             }
           }
           if (EnigmailPrefs.getPref("wrapHtmlBeforeSend")) {
             if (wrapWidth) {
               editor.wrapWidth = wrapWidth - 2; // prepare for the worst case: a 72 char's long line starting with '-'
               editor.rewrap(false);
             }
           }
-        }
-        catch (ex) {}
-      }
-      else {
+        } catch (ex) {}
+      } else {
         // plaintext: Wrapping code has been moved to superordinate function encryptMsg to enable interactive format switch
       }
     }
 
     var exitCodeObj = {};
     var statusFlagsObj = {};
     var errorMsgObj = {};
     var exitCode;
 
     // Get plain text
     // (Do we need to set the nsIDocumentEncoder.* flags?)
-    var origText = this.editorGetContentAs("text/plain",
-      encoderFlags);
-    if (!origText)
+    var origText = this.editorGetContentAs("text/plain", encoderFlags);
+    if (!origText) {
       origText = "";
+    }
 
     if (origText.length > 0) {
       // Sign/encrypt body text
 
       var escText = origText; // Copy plain text for possible escaping
 
       if (sendFlowed && !(sendInfo.sendFlags & ENCRYPT)) {
         // Prevent space stuffing a la RFC 2646 (format=flowed).
@@ -2831,60 +3147,78 @@ Enigmail.msg = {
       this.replaceEditorText(escText);
 
       escText = this.editorGetContentAs("text/plain", encoderFlags);
 
       //EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: escText["+encoderFlags+"] = '"+escText+"'\n");
 
       // Encrypt plaintext
       var charset = this.editorGetCharset();
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: charset=" + charset + "\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.encryptMsg: charset=" +
+          charset +
+          "\n"
+      );
 
       // Encode plaintext to charset from unicode
-      var plainText = (sendInfo.sendFlags & ENCRYPT) ?
-        EnigmailData.convertFromUnicode(origText, charset) :
-        EnigmailData.convertFromUnicode(escText, charset);
-
-      var cipherText = EnigmailEncryption.encryptMessage(window, sendInfo.uiFlags, plainText,
-        sendInfo.fromAddr, sendInfo.toAddr, sendInfo.bccAddr,
+      var plainText =
+        sendInfo.sendFlags & ENCRYPT
+          ? EnigmailData.convertFromUnicode(origText, charset)
+          : EnigmailData.convertFromUnicode(escText, charset);
+
+      var cipherText = EnigmailEncryption.encryptMessage(
+        window,
+        sendInfo.uiFlags,
+        plainText,
+        sendInfo.fromAddr,
+        sendInfo.toAddr,
+        sendInfo.bccAddr,
         sendInfo.sendFlags,
-        exitCodeObj, statusFlagsObj,
-        errorMsgObj);
+        exitCodeObj,
+        statusFlagsObj,
+        errorMsgObj
+      );
 
       exitCode = exitCodeObj.value;
 
       //EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: cipherText = '"+cipherText+"'\n");
-      if (cipherText && (exitCode === 0)) {
+      if (cipherText && exitCode === 0) {
         // Encryption/signing succeeded; overwrite plaintext
 
         if (gMsgCompose.composeHTML) {
           // workaround for Thunderbird bug (TB adds an extra space in front of the text)
           cipherText = "\n" + cipherText;
-        }
-        else
+        } else {
           cipherText = cipherText.replace(/\r\n/g, "\n");
-
-        if ((sendInfo.sendFlags & ENCRYPT) && charset &&
-          (charset.search(/^us-ascii$/i) !== 0)) {
+        }
+
+        if (
+          sendInfo.sendFlags & ENCRYPT &&
+          charset &&
+          charset.search(/^us-ascii$/i) !== 0
+        ) {
           // Add Charset armor header for encrypted blocks
-          cipherText = cipherText.replace(/(-----BEGIN PGP MESSAGE----- *)(\r?\n)/, "$1$2Charset: " + charset + "$2");
+          cipherText = cipherText.replace(
+            /(-----BEGIN PGP MESSAGE----- *)(\r?\n)/,
+            "$1$2Charset: " + charset + "$2"
+          );
         }
 
         // Decode ciphertext from charset to unicode and overwrite
-        this.replaceEditorText(EnigmailData.convertToUnicode(cipherText, charset));
+        this.replaceEditorText(
+          EnigmailData.convertToUnicode(cipherText, charset)
+        );
         //this.enableUndoEncryption(true);
 
         // Save original text (for undo)
         this.processed = {
-          "origText": origText,
-          "charset": charset
+          origText,
+          charset,
         };
-
-      }
-      else {
+      } else {
         // Restore original text
         this.replaceEditorText(origText);
         //this.enableUndoEncryption(false);
 
         if (sendInfo.sendFlags & (ENCRYPT | SIGN)) {
           // Encryption/signing failed
 
           /*if (statusFlagsObj.statusMsg) {
@@ -2899,56 +3233,60 @@ Enigmail.msg = {
           return false;
         }
       }
     }
 
     return true;
   },
 
-
-  sendAborted: function(window, errorMsgObj) {
+  sendAborted(window, errorMsgObj) {
     if (errorMsgObj && errorMsgObj.value) {
       var txt = errorMsgObj.value;
       var txtLines = txt.split(/\r?\n/);
       var errorMsg = "";
       for (var i = 0; i < txtLines.length; ++i) {
         var line = txtLines[i];
         var tokens = line.split(/ /);
         // process most important business reasons for invalid recipient (and sender) errors:
-        if (tokens.length == 3 && (tokens[0] == "INV_RECP" || tokens[0] == "INV_SGNR")) {
+        if (
+          tokens.length == 3 &&
+          (tokens[0] == "INV_RECP" || tokens[0] == "INV_SGNR")
+        ) {
           var reason = tokens[1];
           var key = tokens[2];
           if (reason == "10") {
             errorMsg += EnigmailLocale.getString("keyNotTrusted", [key]) + "\n";
-          }
-          else if (reason == "1") {
+          } else if (reason == "1") {
             errorMsg += EnigmailLocale.getString("keyNotFound", [key]) + "\n";
-          }
-          else if (reason == "4") {
+          } else if (reason == "4") {
             errorMsg += EnigmailLocale.getString("keyRevoked", [key]) + "\n";
-          }
-          else if (reason == "5") {
+          } else if (reason == "5") {
             errorMsg += EnigmailLocale.getString("keyExpired", [key]) + "\n";
           }
         }
       }
       if (errorMsg !== "") {
         txt = errorMsg + "\n" + txt;
       }
-      EnigmailDialog.info(window, EnigmailLocale.getString("sendAborted") + txt);
-    }
-    else {
-      EnigmailDialog.info(window, EnigmailLocale.getString("sendAborted") + "\n" +
-        EnigmailLocale.getString("msgCompose.internalError"));
+      EnigmailDialog.info(
+        window,
+        EnigmailLocale.getString("sendAborted") + txt
+      );
+    } else {
+      EnigmailDialog.info(
+        window,
+        EnigmailLocale.getString("sendAborted") +
+          "\n" +
+          EnigmailLocale.getString("msgCompose.internalError")
+      );
     }
   },
 
-
-  getMailPref: function(prefName) {
+  getMailPref(prefName) {
     let prefRoot = EnigmailPrefs.getPrefRoot();
 
     var prefValue = null;
     try {
       var prefType = prefRoot.getPrefType(prefName);
       // Get pref value
       switch (prefType) {
         case prefRoot.PREF_BOOL:
@@ -2962,110 +3300,124 @@ Enigmail.msg = {
         case prefRoot.PREF_STRING:
           prefValue = prefRoot.getCharPref(prefName);
           break;
 
         default:
           prefValue = undefined;
           break;
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       // Failed to get pref value
-      EnigmailLog.ERROR("enigmailMsgComposeOverlay.js: Enigmail.msg.getMailPref: unknown prefName:" + prefName + " \n");
+      EnigmailLog.ERROR(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.getMailPref: unknown prefName:" +
+          prefName +
+          " \n"
+      );
     }
 
     return prefValue;
   },
 
-  messageSendCheck: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.messageSendCheck\n");
+  messageSendCheck() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.messageSendCheck\n"
+    );
 
     try {
       var warn = this.getMailPref("mail.warn_on_send_accel_key");
 
       if (warn) {
         var checkValue = {
-          value: false
+          value: false,
         };
         var bundle = document.getElementById("bundle_composeMsgs");
-        var buttonPressed = EnigmailDialog.getPromptSvc().confirmEx(window,
-          bundle.getString('sendMessageCheckWindowTitle'),
-          bundle.getString('sendMessageCheckLabel'), (EnigmailDialog.getPromptSvc().BUTTON_TITLE_IS_STRING * EnigmailDialog.getPromptSvc().BUTTON_POS_0) +
-          (EnigmailDialog.getPromptSvc().BUTTON_TITLE_CANCEL * EnigmailDialog.getPromptSvc().BUTTON_POS_1),
-          bundle.getString('sendMessageCheckSendButtonLabel'),
-          null, null,
-          bundle.getString('CheckMsg'),
-          checkValue);
+        var buttonPressed = EnigmailDialog.getPromptSvc().confirmEx(
+          window,
+          bundle.getString("sendMessageCheckWindowTitle"),
+          bundle.getString("sendMessageCheckLabel"),
+          EnigmailDialog.getPromptSvc().BUTTON_TITLE_IS_STRING *
+            EnigmailDialog.getPromptSvc().BUTTON_POS_0 +
+            EnigmailDialog.getPromptSvc().BUTTON_TITLE_CANCEL *
+              EnigmailDialog.getPromptSvc().BUTTON_POS_1,
+          bundle.getString("sendMessageCheckSendButtonLabel"),
+          null,
+          null,
+          bundle.getString("CheckMsg"),
+          checkValue
+        );
         if (buttonPressed !== 0) {
           return false;
         }
         if (checkValue.value) {
-          EnigmailPrefs.getPrefRoot().setBoolPref("mail.warn_on_send_accel_key", false);
+          EnigmailPrefs.getPrefRoot().setBoolPref(
+            "mail.warn_on_send_accel_key",
+            false
+          );
         }
       }
-    }
-    catch (ex) {}
+    } catch (ex) {}
 
     return true;
   },
 
-
   /**
    * set non-standard message Header
    * (depending on TB version)
    *
    * hdr: String: header type (e.g. X-Enigmail-Version)
    * val: String: header data (e.g. 1.2.3.4)
    */
-  setAdditionalHeader: function(hdr, val) {
+  setAdditionalHeader(hdr, val) {
     if ("otherRandomHeaders" in gMsgCompose.compFields) {
       // TB <= 36
       gMsgCompose.compFields.otherRandomHeaders += hdr + ": " + val + "\r\n";
-    }
-    else {
+    } else {
       gMsgCompose.compFields.setHeader(hdr, val);
     }
   },
 
-  unsetAdditionalHeader: function(hdr) {
+  unsetAdditionalHeader(hdr) {
     if ("otherRandomHeaders" in gMsgCompose.compFields) {
       // TB <= 36
       let h = gMsgCompose.compFields.otherRandomHeaders;
       let r = new RegExp("^(" + hdr + ":)(.*)$", "im");
       let m = h.replace(r, "").replace(/(\r\n)+/, "\r\n");
       gMsgCompose.compFields.otherRandomHeaders = m;
-    }
-    else {
+    } else {
       gMsgCompose.compFields.deleteHeader(hdr);
     }
   },
 
   // called just before sending
-  modifyCompFields: function() {
+  modifyCompFields() {
     try {
-
       if (!this.identity) {
         this.identity = getCurrentIdentity();
       }
 
       if (Enigmail.msg.isEnigmailEnabledForIdentity()) {
         if (EnigmailPrefs.getPref("addHeaders")) {
-          this.setAdditionalHeader("X-Enigmail-Version", EnigmailApp.getVersion());
+          this.setAdditionalHeader(
+            "X-Enigmail-Version",
+            EnigmailApp.getVersion()
+          );
         }
 
         //this.setAutocryptHeader();
       }
-    }
-    catch (ex) {
-      EnigmailLog.writeException("enigmailMsgComposeOverlay.js: Enigmail.msg.modifyCompFields", ex);
+    } catch (ex) {
+      EnigmailLog.writeException(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.modifyCompFields",
+        ex
+      );
     }
   },
 
-  getCurrentIncomingServer: function() {
+  getCurrentIncomingServer() {
     let currentAccountKey = getCurrentAccountKey();
     let account = MailServices.accounts.getAccount(currentAccountKey);
 
     return account.incomingServer; /* returns nsIMsgIncomingServer */
   },
 
   /*
   setAutocryptHeader: function() {
@@ -3095,26 +3447,27 @@ Enigmail.msg = {
       if (k.exitCode === 0) {
         let keyData = " " + k.keyData.replace(/(.{72})/g, "$1\r\n ").replace(/\r\n $/, "");
         this.setAdditionalHeader('Autocrypt', 'addr=' + fromMail + prefMutual + '; keydata=\r\n' + keyData);
       }
     }
   },
   */
 
-  fromChangedListener: function(event) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.fromChangedListener\n");
+  fromChangedListener(event) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.fromChangedListener\n"
+    );
 
     /* TODO:
      * reset gSendSigned, gAttachMyPublicPGPKey, gSendEncrypted, gOptionalEncryption
      * to account's default setting, but only if settings haven't been touched
      * by the user in this composer windows, i.e. check
      * gUserTouchedSendEncrypted, gUserTouchedSendSigned, gUserTouchedAttachMyPubKey
      */
-    return;
 
     /*
   if (!gSMFields) {
     return;
   }
 
   var encryptionPolicy = gCurrentIdentity.getIntAttribute("encryptionpolicy");
   var useEncryption = false;
@@ -3159,111 +3512,139 @@ Enigmail.msg = {
   }
   gSMFields.signMessage = useSigning;
   if (useSigning) {
     setSignatureUI();
   } else {
     setNoSignatureUI();
   }
     */
-
   },
 
   /**
    * Perform handling of the compose-send-message' event from TB (or SendLater)
    */
 
   /**
    * Handle the 'compose-send-message' event from TB
    */
-  sendMessageListener: function(event) {
+  sendMessageListener(event) {
     console.debug("in Enigmail.msg.sendMessageListener");
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.sendMessageListener\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.sendMessageListener\n"
+    );
 
     if (!gSelectedTechnologyIsPGP) {
       return;
     }
-    
+
     let msgcomposeWindow = document.getElementById("msgcomposeWindow");
     let sendMsgType = Number(msgcomposeWindow.getAttribute("msgtype"));
 
-    if (!this.sendProcess || sendMsgType != Components.interfaces.nsIMsgCompDeliverMode.AutoSaveAsDraft) {
+    if (
+      !this.sendProcess ||
+      sendMsgType != Ci.nsIMsgCompDeliverMode.AutoSaveAsDraft
+    ) {
       this.sendProcess = true;
       //let bc = document.getElementById("enigmail-bc-sendprocess");
 
       try {
         this.modifyCompFields();
         //bc.setAttribute("disabled", "true");
         if (!this.encryptMsg(sendMsgType)) {
           this.resetUpdatedFields();
           event.preventDefault();
           event.stopPropagation();
         }
-      }
-      catch (ex) {
+      } catch (ex) {
         console.debug(ex);
       }
       //bc.removeAttribute("disabled");
-    }
-    else {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.sendMessageListener: sending in progress - autosave aborted\n");
+    } else {
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.sendMessageListener: sending in progress - autosave aborted\n"
+      );
       event.preventDefault();
       event.stopPropagation();
     }
     this.sendProcess = false;
   },
 
-  toggleAttribute: function(attrName) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.toggleAttribute('" + attrName + "')\n");
-
-    var menuElement = document.getElementById("enigmail_" + attrName);
+  toggleAttribute(attrName) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.toggleAttribute('" +
+        attrName +
+        "')\n"
+    );
 
     var oldValue = EnigmailPrefs.getPref(attrName);
     EnigmailPrefs.setPref(attrName, !oldValue);
   },
 
-  toggleAccountAttr: function(attrName) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.toggleAccountAttr('" + attrName + "')\n");
+  toggleAccountAttr(attrName) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.toggleAccountAttr('" +
+        attrName +
+        "')\n"
+    );
 
     var oldValue = this.identity.getBoolAttribute(attrName);
     this.identity.setBoolAttribute(attrName, !oldValue);
-
   },
 
-  decryptQuote: function(interactive) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: " + interactive + "\n");
-
-    if (gWindowLocked || this.processed)
+  decryptQuote(interactive) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: " +
+        interactive +
+        "\n"
+    );
+
+    if (gWindowLocked || this.processed) {
       return;
+    }
 
     var enigmailSvc = EnigmailCore.getService(window);
-    if (!enigmailSvc)
+    if (!enigmailSvc) {
       return;
-
-    const dce = Components.interfaces.nsIDocumentEncoder;
+    }
+
+    const dce = Ci.nsIDocumentEncoder;
     var encoderFlags = dce.OutputFormatted | dce.OutputLFLineBreak;
 
     var docText = this.editorGetContentAs("text/plain", encoderFlags);
 
     var blockBegin = docText.indexOf("-----BEGIN PGP ");
-    if (blockBegin < 0)
+    if (blockBegin < 0) {
       return;
+    }
 
     // Determine indentation string
     var indentBegin = docText.substr(0, blockBegin).lastIndexOf("\n");
     var indentStr = docText.substring(indentBegin + 1, blockBegin);
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: indentStr='" + indentStr + "'\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: indentStr='" +
+        indentStr +
+        "'\n"
+    );
 
     var beginIndexObj = {};
     var endIndexObj = {};
     var indentStrObj = {};
-    var blockType = EnigmailArmor.locateArmoredBlock(docText, 0, indentStr, beginIndexObj, endIndexObj, indentStrObj);
-    if ((blockType != "MESSAGE") && (blockType != "SIGNED MESSAGE"))
+    var blockType = EnigmailArmor.locateArmoredBlock(
+      docText,
+      0,
+      indentStr,
+      beginIndexObj,
+      endIndexObj,
+      indentStrObj
+    );
+    if (blockType != "MESSAGE" && blockType != "SIGNED MESSAGE") {
       return;
+    }
 
     var beginIndex = beginIndexObj.value;
     var endIndex = endIndexObj.value;
 
     var head = docText.substr(0, beginIndex);
     var tail = docText.substr(endIndex + 1);
 
     var pgpBlock = docText.substr(beginIndex, endIndex - beginIndex + 1);
@@ -3283,39 +3664,45 @@ Enigmail.msg = {
 
       if (indentStr.match(/[ \t]*$/)) {
         indentStr = indentStr.replace(/[ \t]*$/gm, "");
         indentRegexp = new RegExp("^" + indentStr + "$", "gm");
 
         pgpBlock = pgpBlock.replace(indentRegexp, "");
       }
 
-
       // Handle blank indented lines
       pgpBlock = pgpBlock.replace(/^[ \t]*>[ \t]*$/gm, "");
       //tail     =     tail.replace(/^[ \t]*>[ \t]*$/g, "");
 
       // Trim leading space in tail
       tail = tail.replace(/^\s*\n/m, "\n");
     }
 
     if (tail.search(/\S/) < 0) {
       // No non-space characters in tail; delete it
       tail = "";
     }
 
     //EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: pgpBlock='"+pgpBlock+"'\n");
 
     var charset = this.editorGetCharset();
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: charset=" + charset + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: charset=" +
+        charset +
+        "\n"
+    );
 
     // Encode ciphertext from unicode to charset
     var cipherText = EnigmailData.convertFromUnicode(pgpBlock, charset);
 
-    if ((!this.getMailPref("mailnews.reply_in_default_charset")) && (blockType == "MESSAGE")) {
+    if (
+      !this.getMailPref("mailnews.reply_in_default_charset") &&
+      blockType == "MESSAGE"
+    ) {
       // set charset according to PGP block, if available (encrypted messages only)
       let armorHeaders = EnigmailArmor.getArmorHeaders(cipherText);
 
       if ("charset" in armorHeaders) {
         charset = armorHeaders.charset;
         gMsgCompose.SetDocumentCharset(charset);
       }
     }
@@ -3331,134 +3718,168 @@ Enigmail.msg = {
     var errorMsgObj = {};
     var blockSeparationObj = {};
     var encToDetailsObj = {};
 
     var uiFlags = EnigmailConstants.UI_UNVERIFIED_ENC_OK;
 
     var plainText = "";
 
-    plainText = EnigmailDecryption.decryptMessage(window, uiFlags, cipherText,
-      signatureObj, exitCodeObj, statusFlagsObj,
-      keyIdObj, userIdObj, sigDetailsObj,
-      errorMsgObj, blockSeparationObj, encToDetailsObj);
+    plainText = EnigmailDecryption.decryptMessage(
+      window,
+      uiFlags,
+      cipherText,
+      signatureObj,
+      exitCodeObj,
+      statusFlagsObj,
+      keyIdObj,
+      userIdObj,
+      sigDetailsObj,
+      errorMsgObj,
+      blockSeparationObj,
+      encToDetailsObj
+    );
     // Decode plaintext from charset to unicode
-    plainText = EnigmailData.convertToUnicode(plainText, charset).replace(/\r\n/g, "\n");
+    plainText = EnigmailData.convertToUnicode(plainText, charset).replace(
+      /\r\n/g,
+      "\n"
+    );
 
     //if (EnigmailPrefs.getPref("keepSettingsForReply")) {
-      if (statusFlagsObj.value & EnigmailConstants.DECRYPTION_OKAY) {
-        //this.setSendMode('encrypt');
-        gIsRelatedToEncryptedOriginal = true;
-        gSendEncrypted = true;
-      }
+    if (statusFlagsObj.value & EnigmailConstants.DECRYPTION_OKAY) {
+      //this.setSendMode('encrypt');
+      gIsRelatedToEncryptedOriginal = true;
+      gSendEncrypted = true;
+    }
     //}
 
     var exitCode = exitCodeObj.value;
 
     if (exitCode !== 0) {
       // Error processing
       var errorMsg = errorMsgObj.value;
 
       var statusLines = errorMsg.split(/\r?\n/);
 
       var displayMsg;
       if (statusLines && statusLines.length) {
         // Display only first ten lines of error message
-        while (statusLines.length > 10)
+        while (statusLines.length > 10) {
           statusLines.pop();
+        }
 
         displayMsg = statusLines.join("\n");
 
-        if (interactive)
+        if (interactive) {
           EnigmailDialog.info(window, displayMsg);
+        }
       }
     }
 
     if (blockType == "MESSAGE" && exitCode === 0 && plainText.length === 0) {
       plainText = " ";
     }
 
     if (!plainText) {
-      if (blockType != "SIGNED MESSAGE")
+      if (blockType != "SIGNED MESSAGE") {
         return;
+      }
 
       // Extract text portion of clearsign block
-      plainText = EnigmailArmor.extractSignaturePart(pgpBlock, EnigmailConstants.SIGNATURE_TEXT);
+      plainText = EnigmailArmor.extractSignaturePart(
+        pgpBlock,
+        EnigmailConstants.SIGNATURE_TEXT
+      );
     }
 
-    const nsIMsgCompType = Components.interfaces.nsIMsgCompType;
+    const nsIMsgCompType = Ci.nsIMsgCompType;
     var doubleDashSeparator = EnigmailPrefs.getPref("doubleDashSeparator");
-    if (gMsgCompose.type != nsIMsgCompType.Template &&
+    if (
+      gMsgCompose.type != nsIMsgCompType.Template &&
       gMsgCompose.type != nsIMsgCompType.Draft &&
-      doubleDashSeparator) {
+      doubleDashSeparator
+    ) {
       var signOffset = plainText.search(/[\r\n]-- +[\r\n]/);
 
       if (signOffset < 0 && blockType == "SIGNED MESSAGE") {
         signOffset = plainText.search(/[\r\n]--[\r\n]/);
       }
 
       if (signOffset > 0) {
         // Strip signature portion of quoted message
         plainText = plainText.substr(0, signOffset + 1);
       }
     }
 
-    var clipBoard = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
+    var clipBoard = Services.clipboard;
     var data;
     if (clipBoard.supportsSelectionClipboard()) {
       // get the clipboard contents for selected text (X11)
-      data = EnigmailClipboard.getClipboardContent(window, Components.interfaces.nsIClipboard.kSelectionClipboard);
+      data = EnigmailClipboard.getClipboardContent(
+        window,
+        Ci.nsIClipboard.kSelectionClipboard
+      );
     }
 
     // Replace encrypted quote with decrypted quote (destroys selection clipboard on X11)
     this.editorSelectAll();
 
     //EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: plainText='"+plainText+"'\n");
 
-    if (head)
+    if (head) {
       this.editorInsertText(head);
+    }
 
     var quoteElement;
 
     if (indentStr) {
       quoteElement = this.editorInsertAsQuotation(plainText);
-
-    }
-    else {
+    } else {
       this.editorInsertText(plainText);
     }
 
-    if (tail)
+    if (tail) {
       this.editorInsertText(tail);
+    }
 
     if (statusFlagsObj.value & EnigmailConstants.DECRYPTION_OKAY) {
       this.checkInlinePgpReply(head, tail);
     }
 
     if (clipBoard.supportsSelectionClipboard()) {
       // restore the clipboard contents for selected text (X11)
-      EnigmailClipboard.setClipboardContent(data, clipBoard.kSelectionClipboard);
+      EnigmailClipboard.setClipboardContent(
+        data,
+        clipBoard.kSelectionClipboard
+      );
     }
 
-    if (interactive)
+    if (interactive) {
       return;
+    }
 
     // Position cursor
     var replyOnTop = 1;
     try {
       replyOnTop = this.identity.replyOnTop;
-    }
-    catch (ex) {}
-
-    if (!indentStr || !quoteElement)
+    } catch (ex) {}
+
+    if (!indentStr || !quoteElement) {
       replyOnTop = 1;
-
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: replyOnTop=" + replyOnTop + ", quoteElement=" + quoteElement + "\n");
-
-    var nsISelectionController = Components.interfaces.nsISelectionController;
+    }
+
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.decryptQuote: replyOnTop=" +
+        replyOnTop +
+        ", quoteElement=" +
+        quoteElement +
+        "\n"
+    );
+
+    var nsISelectionController = Ci.nsISelectionController;
 
     if (this.editor.selectionController) {
       var selection = this.editor.selectionController;
       selection.completeMove(false, false); // go to start;
 
       switch (replyOnTop) {
         case 0:
           // Position after quote
@@ -3489,93 +3910,109 @@ Enigmail.msg = {
         default:
           // Position at beginning of document
 
           if (this.editor) {
             this.editor.beginningOfDocument();
           }
       }
 
-      this.editor.selectionController.scrollSelectionIntoView(nsISelectionController.SELECTION_NORMAL,
+      this.editor.selectionController.scrollSelectionIntoView(
+        nsISelectionController.SELECTION_NORMAL,
         nsISelectionController.SELECTION_ANCHOR_REGION,
-        true);
+        true
+      );
     }
 
     //this.processFinalState();
     this.updateStatusBar();
   },
 
-  checkInlinePgpReply: function(head, tail) {
-    const CT = Components.interfaces.nsIMsgCompType;
-    if (!this.identity) return;
-
-    let hLines = (head.search(/[^\s>]/) < 0 ? 0 : 1);
+  checkInlinePgpReply(head, tail) {
+    const CT = Ci.nsIMsgCompType;
+    if (!this.identity) {
+      return;
+    }
+
+    let hLines = head.search(/[^\s>]/) < 0 ? 0 : 1;
 
     if (hLines > 0) {
       switch (gMsgCompose.type) {
         case CT.Reply:
         case CT.ReplyAll:
         case CT.ReplyToSender:
         case CT.ReplyToGroup:
         case CT.ReplyToSenderAndGroup:
         case CT.ReplyToList: {
           // if head contains at only a few line of text, we assume it's the
           // header above the quote (e.g. XYZ wrote:) and the user's signature
 
           let h = head.split(/\r?\n/);
           hLines = -1;
 
           for (let i = 0; i < h.length; i++) {
-            if (h[i].search(/[^\s>]/) >= 0) hLines++;
+            if (h[i].search(/[^\s>]/) >= 0) {
+              hLines++;
+            }
           }
         }
       }
     }
 
     if (hLines > 0 && (!this.identity.sigOnReply || this.identity.sigBottom)) {
       // display warning if no signature on top of message
       this.displayPartialEncryptedWarning();
-    }
-    else if (hLines > 10) {
+    } else if (hLines > 10) {
       this.displayPartialEncryptedWarning();
-    }
-    else if (tail.search(/[^\s>]/) >= 0 && !(this.identity.sigOnReply && this.identity.sigBottom)) {
+    } else if (
+      tail.search(/[^\s>]/) >= 0 &&
+      !(this.identity.sigOnReply && this.identity.sigBottom)
+    ) {
       // display warning if no signature below message
       this.displayPartialEncryptedWarning();
     }
   },
 
-  editorInsertText: function(plainText) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertText\n");
+  editorInsertText(plainText) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertText\n"
+    );
     if (this.editor) {
       var mailEditor;
       try {
-        mailEditor = this.editor.QueryInterface(Components.interfaces.nsIEditorMailSupport);
+        mailEditor = this.editor.QueryInterface(Ci.nsIEditorMailSupport);
         mailEditor.insertTextWithQuotations(plainText);
-      }
-      catch (ex) {
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertText: no mail editor\n");
+      } catch (ex) {
+        EnigmailLog.DEBUG(
+          "enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertText: no mail editor\n"
+        );
         this.editor.insertText(plainText);
       }
     }
   },
 
-  editorInsertAsQuotation: function(plainText) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertAsQuotation\n");
+  editorInsertAsQuotation(plainText) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertAsQuotation\n"
+    );
     if (this.editor) {
       var mailEditor;
       try {
-        mailEditor = this.editor.QueryInterface(Components.interfaces.nsIEditorMailSupport);
+        mailEditor = this.editor.QueryInterface(Ci.nsIEditorMailSupport);
+      } catch (ex) {}
+
+      if (!mailEditor) {
+        return 0;
       }
-      catch (ex) {}
-
-      if (!mailEditor)
-        return 0;
-
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertAsQuotation: mailEditor=" + mailEditor + "\n");
+
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.editorInsertAsQuotation: mailEditor=" +
+          mailEditor +
+          "\n"
+      );
 
       mailEditor.insertAsCitedQuotation(plainText, "", false);
 
       return 1;
     }
     return 0;
   },
 
@@ -3583,17 +4020,17 @@ Enigmail.msg = {
    * Display a notification to the user at the bottom of the window
    *
    * @param priority: Number    - Priority of the message [1 = high (error) ... 3 = low (info)]
    * @param msgText: String     - Text to be displayed in notification bar
    * @param messageId: String   - Unique message type identification
    * @param detailsText: String - optional text to be displayed by clicking on "Details" button.
    *                              if null or "", then the Detail button will no be displayed.
    */
-  notifyUser: function(priority, msgText, messageId, detailsText) {
+  notifyUser(priority, msgText, messageId, detailsText) {
     let notif = document.getElementById("attachmentNotificationBox");
     if (!notif) {
       notif = gNotification.notificationbox;
     }
     let prio;
 
     switch (priority) {
       case 1:
@@ -3605,156 +4042,170 @@ Enigmail.msg = {
       default:
         prio = notif.PRIORITY_WARNING_MEDIUM;
     }
 
     let buttonArr = [];
 
     if (detailsText && detailsText.length > 0) {
       buttonArr.push({
-        accessKey: EnigmailLocale.getString("msgCompose.detailsButton.accessKey"),
+        accessKey: EnigmailLocale.getString(
+          "msgCompose.detailsButton.accessKey"
+        ),
         label: EnigmailLocale.getString("msgCompose.detailsButton.label"),
-        callback: function(aNotificationBar, aButton) {
+        callback(aNotificationBar, aButton) {
           EnigmailDialog.info(window, detailsText);
-        }
+        },
       });
     }
     notif.appendNotification(msgText, messageId, null, prio, buttonArr);
   },
 
   /**
    * Display a warning message if we are replying to or forwarding
    * a partially decrypted inline-PGP email
    */
-  displayPartialEncryptedWarning: function() {
-    let msgLong = EnigmailLocale.getString("msgCompose.partiallyEncrypted.inlinePGP");
-
-    this.notifyUser(1, EnigmailLocale.getString("msgCompose.partiallyEncrypted.short"), "notifyPartialDecrypt", msgLong);
+  displayPartialEncryptedWarning() {
+    let msgLong = EnigmailLocale.getString(
+      "msgCompose.partiallyEncrypted.inlinePGP"
+    );
+
+    this.notifyUser(
+      1,
+      EnigmailLocale.getString("msgCompose.partiallyEncrypted.short"),
+      "notifyPartialDecrypt",
+      msgLong
+    );
   },
 
-  editorSelectAll: function() {
+  editorSelectAll() {
     if (this.editor) {
       this.editor.selectAll();
     }
   },
 
-  editorGetCharset: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.editorGetCharset\n");
+  editorGetCharset() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.editorGetCharset\n"
+    );
     return this.editor.documentCharacterSet;
   },
 
-  editorGetContentAs: function(mimeType, flags) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.editorGetContentAs\n");
+  editorGetContentAs(mimeType, flags) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.editorGetContentAs\n"
+    );
     if (this.editor) {
       return this.editor.outputToString(mimeType, flags);
     }
 
     return null;
   },
 
   addrOnChangeTimer: null,
 
-  addressOnChange: function() {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.addressOnChange\n");
+  addressOnChange() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: Enigmail.msg.addressOnChange\n"
+    );
     if (!this.addrOnChangeTimer) {
       var self = this;
-      this.addrOnChangeTimer = EnigmailTimer.setTimeout(function _f() {
+      this.addrOnChangeTimer = EnigmailTimer.setTimeout(function() {
         self.fireSendFlags();
         self.addrOnChangeTimer = null;
       }, Enigmail.msg.addrOnChangeTimeout);
     }
   },
 
-  focusChange: function() {
+  focusChange() {
     // call original TB function
     CommandUpdate_MsgCompose();
 
     var focusedWindow = top.document.commandDispatcher.focusedWindow;
 
     // we're just setting focus to where it was before
     if (focusedWindow == Enigmail.msg.lastFocusedWindow) {
       // skip
       return;
     }
 
     Enigmail.msg.lastFocusedWindow = focusedWindow;
 
     Enigmail.msg.fireSendFlags();
   },
 
-  fireSendFlags: function() {
+  fireSendFlags() {
     try {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.fireSendFlags\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: Enigmail.msg.fireSendFlags\n"
+      );
       if (!this.determineSendFlagId) {
         let self = this;
-        this.determineSendFlagId = EnigmailTimer.setTimeout(
-          function _sendFlagWrapper() {
-            try {
-              self.determineSendFlags();
-              self.fireSearchKeys();
-            }
-            catch (x) {}
-            self.determineSendFlagId = null;
-          },
-          0);
+        this.determineSendFlagId = EnigmailTimer.setTimeout(function() {
+          try {
+            self.determineSendFlags();
+            self.fireSearchKeys();
+          } catch (x) {}
+          self.determineSendFlagId = null;
+        }, 0);
       }
-    }
-    catch (ex) {}
+    } catch (ex) {}
   },
 
   /**
    * Merge multiple  Re: Re: into one Re: in message subject
    */
-  fixMessageSubject: function() {
+  fixMessageSubject() {
     let subjElem = document.getElementById("msgSubject");
     if (subjElem) {
       let r = subjElem.value.replace(/^(Re: )+/, "Re: ");
       if (r !== subjElem.value) {
         subjElem.value = r;
-        if (typeof subjElem.oninput === "function") subjElem.oninput();
+        if (typeof subjElem.oninput === "function") {
+          subjElem.oninput();
+        }
       }
     }
   },
 
-  fireSearchKeys: function() {
+  fireSearchKeys() {
     if (Enigmail.msg.isEnigmailEnabledForIdentity()) {
-
-      if (this.searchKeysTimeout) return;
+      if (this.searchKeysTimeout) {
+        return;
+      }
 
       let self = this;
 
-      this.searchKeysTimeout = EnigmailTimer.setTimeout(function _f() {
-          self.searchKeysTimeout = null;
-          Enigmail.msg.findMissingKeys();
-        },
-        5000); // 5 Seconds
+      this.searchKeysTimeout = EnigmailTimer.setTimeout(function() {
+        self.searchKeysTimeout = null;
+        Enigmail.msg.findMissingKeys();
+      }, 5000); // 5 Seconds
     }
   },
 
   /**
    * Determine if all addressees have a valid key ID; if not, attempt to
    * import them via WKD or Autocrypt.
    */
-  findMissingKeys: async function() {
-
+  async findMissingKeys() {
     try {
       EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: findMissingKeys()\n");
 
       let missingKeys = this.determineSendFlags();
 
       if ("errArray" in missingKeys && missingKeys.errArray.length > 0) {
         let missingEmails = missingKeys.errArray.map(function(i) {
           return i.addr.toLowerCase().trim();
         });
 
         let lookupList = [];
 
         // only search for keys not checked before
         for (let k of missingEmails) {
-          if (this.keyLookupDone.indexOf(k) < 0) {
+          if (!this.keyLookupDone.includes(k)) {
             lookupList.push(k);
             this.keyLookupDone.push(k);
           }
         }
 
         if (lookupList.length > 0) {
           try {
             let foundKeys;
@@ -3767,159 +4218,184 @@ Enigmail.msg = {
                 this.determineSendFlags();
               }
             }
             */
 
             if (EnigmailPrefs.getPref("autoWkdLookup") === 0) {
               return;
             }
-            
+
             // old buggy: if autocrypt is disabled, foundKeys is still undefined
             // if (foundKeys.length >= lookupList.length) return;
 
             foundKeys = await EnigmailWkdLookup.findKeys(lookupList);
-            EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: findMissingKeys: wkd got " + foundKeys + "\n");
+            EnigmailLog.DEBUG(
+              "enigmailMsgComposeOverlay.js: findMissingKeys: wkd got " +
+                foundKeys +
+                "\n"
+            );
             if (foundKeys) {
               this.determineSendFlags();
             }
-          }
-          catch (err) {
-            EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: findMissingKeys: error " + err + "\n");
+          } catch (err) {
+            EnigmailLog.DEBUG(
+              "enigmailMsgComposeOverlay.js: findMissingKeys: error " +
+                err +
+                "\n"
+            );
           }
         }
       }
-    }
-    catch (ex) {}
-  }
+    } catch (ex) {}
+  },
 };
 
-
 Enigmail.composeStateListener = {
-  NotifyComposeFieldsReady: function() {
+  NotifyComposeFieldsReady() {
     // Note: NotifyComposeFieldsReady is only called when a new window is created (i.e. not in case a window object is reused).
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: ECSL.NotifyComposeFieldsReady\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: ECSL.NotifyComposeFieldsReady\n"
+    );
 
     try {
-      Enigmail.msg.editor = gMsgCompose.editor.QueryInterface(Components.interfaces.nsIEditor);
+      Enigmail.msg.editor = gMsgCompose.editor.QueryInterface(Ci.nsIEditor);
+    } catch (ex) {}
+
+    if (!Enigmail.msg.editor) {
+      return;
     }
-    catch (ex) {}
-
-    if (!Enigmail.msg.editor)
-      return;
 
     Enigmail.msg.fixMessageSubject();
 
     function enigDocStateListener() {}
 
     enigDocStateListener.prototype = {
-      QueryInterface: function(iid) {
-        if (!iid.equals(Components.interfaces.nsIDocumentStateListener) &&
-          !iid.equals(Components.interfaces.nsISupports))
-          throw Components.results.NS_ERROR_NO_INTERFACE;
-
-        return this;
+      QueryInterface: ChromeUtils.generateQI(["nsIDocumentStateListener"]),
+
+      NotifyDocumentWillBeDestroyed() {
+        EnigmailLog.DEBUG(
+          "enigmailMsgComposeOverlay.js: EDSL.enigDocStateListener.NotifyDocumentWillBeDestroyed\n"
+        );
       },
 
-      NotifyDocumentWillBeDestroyed: function() {
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: EDSL.enigDocStateListener.NotifyDocumentWillBeDestroyed\n");
+      NotifyDocumentStateChanged(nowDirty) {
+        EnigmailLog.DEBUG(
+          "enigmailMsgComposeOverlay.js: EDSL.enigDocStateListener.NotifyDocumentStateChanged\n"
+        );
       },
-
-      NotifyDocumentStateChanged: function(nowDirty) {
-        EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: EDSL.enigDocStateListener.NotifyDocumentStateChanged\n");
-      }
     };
 
     var docStateListener = new enigDocStateListener();
 
     Enigmail.msg.editor.addDocumentStateListener(docStateListener);
   },
 
-  ComposeProcessDone: function(aResult) {
+  ComposeProcessDone(aResult) {
     // Note: called after a mail was sent (or saved)
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: ECSL.ComposeProcessDone: " + aResult + "\n");
-
-    if (aResult != Components.results.NS_OK) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: ECSL.ComposeProcessDone: " + aResult + "\n"
+    );
+
+    if (aResult != Cr.NS_OK) {
       if (Enigmail.msg.processed) {
         //Enigmail.msg.undoEncryption(4);
       }
       Enigmail.msg.removeAttachedKey();
     }
 
     // ensure that securityInfo is set back to S/MIME flags (especially required if draft was saved)
-    if (gSMFields) Enigmail.msg.setSecurityParams(gSMFields);
+    if (gSMFields) {
+      Enigmail.msg.setSecurityParams(gSMFields);
+    }
   },
 
-  NotifyComposeBodyReady: function() {
+  NotifyComposeBodyReady() {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: ECSL.ComposeBodyReady\n");
 
-    var isEmpty,
-      isEditable;
+    var isEmpty, isEditable;
 
     isEmpty = Enigmail.msg.editor.documentIsEmpty;
     isEditable = Enigmail.msg.editor.isDocumentEditable;
     Enigmail.msg.composeBodyReady = true;
 
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: ECSL.ComposeBodyReady: isEmpty=" + isEmpty + ", isEditable=" + isEditable + "\n");
+    EnigmailLog.DEBUG(
+      "enigmailMsgComposeOverlay.js: ECSL.ComposeBodyReady: isEmpty=" +
+        isEmpty +
+        ", isEditable=" +
+        isEditable +
+        "\n"
+    );
 
     /*
     if (Enigmail.msg.disableSmime) {
       if (gMsgCompose && gMsgCompose.compFields && Enigmail.msg.getSecurityParams()) {
         let si = Enigmail.msg.getSecurityParams(null, true);
         si.signMessage = false;
         si.requireEncryptMessage = false;
       }
       else {
         EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: ECSL.ComposeBodyReady: could not disable S/MIME\n");
       }
     }
     */
 
-    if (!isEditable || isEmpty)
+    if (!isEditable || isEmpty) {
       return;
+    }
 
     let msgHdr = Enigmail.msg.getMsgHdr();
     if (msgHdr) {
       Enigmail.msg.setOriginalSubject(msgHdr.subject, true);
     }
     Enigmail.msg.fixMessageSubject();
 
     if (!Enigmail.msg.timeoutId && !Enigmail.msg.dirty) {
       Enigmail.msg.timeoutId = EnigmailTimer.setTimeout(function() {
-          Enigmail.msg.decryptQuote(false);
-        },
-        0);
+        Enigmail.msg.decryptQuote(false);
+      }, 0);
     }
   },
 
-  SaveInFolderDone: function(folderURI) {
+  SaveInFolderDone(folderURI) {
     //EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: ECSL.SaveInFolderDone\n");
-  }
+  },
 };
 
-
 /**
  * Unload Enigmail for update or uninstallation
  */
-Enigmail.composeUnload = function _unload_Enigmail() {
-  window.removeEventListener("unload-enigmail", Enigmail.composeUnload, false);
-  window.removeEventListener("load-enigmail", Enigmail.msg.composeStartup, false);
-  window.removeEventListener("compose-window-unload", Enigmail.msg.msgComposeClose, true);
-  window.removeEventListener("compose-send-message", Enigmail.msg.sendMessageListener, true);
-  window.removeEventListener("compose-from-changed", Enigmail.msg.fromChangedListener, true);
+Enigmail.composeUnload = function() {
+  window.removeEventListener("unload-enigmail", Enigmail.composeUnload);
+  window.removeEventListener("load-enigmail", Enigmail.msg.composeStartup);
+  window.removeEventListener(
+    "compose-window-unload",
+    Enigmail.msg.msgComposeClose,
+    true
+  );
+  window.removeEventListener(
+    "compose-send-message",
+    Enigmail.msg.sendMessageListener,
+    true
+  );
+  window.removeEventListener(
+    "compose-from-changed",
+    Enigmail.msg.fromChangedListener,
+    true
+  );
 
   gMsgCompose.UnregisterStateListener(Enigmail.composeStateListener);
 
   let msgId = document.getElementById("msgIdentityPopup");
   if (msgId) {
-    msgId.removeEventListener("command", Enigmail.msg.setIdentityCallback, false);
+    msgId.removeEventListener("command", Enigmail.msg.setIdentityCallback);
   }
 
   let subj = document.getElementById("msgSubject");
-  subj.removeEventListener('focus', Enigmail.msg.fireSendFlags, false);
+  subj.removeEventListener("focus", Enigmail.msg.fireSendFlags);
 
   // check rules for status bar icons on each change of the recipients
   let rep = new RegExp("; Enigmail.msg.addressOnChange\\(this\\);");
   var adrCol = document.getElementById("addressCol2#1"); // recipients field
   if (adrCol) {
     let attr = adrCol.getAttribute("oninput");
     adrCol.setAttribute("oninput", attr.replace(rep, ""));
     attr = adrCol.getAttribute("onchange");
@@ -3930,17 +4406,23 @@ Enigmail.composeUnload = function _unloa
     let attr = adrCol.getAttribute("oncommand");
     adrCol.setAttribute("oncommand", attr.replace(rep, ""));
   }
 
   // finally unload Enigmail entirely
   Enigmail = undefined;
 };
 
-addEventListener("load", Enigmail.msg.composeStartup.bind(Enigmail.msg), { capture: false, once: true });
-
-window.addEventListener("unload-enigmail",
-  Enigmail.composeUnload.bind(Enigmail.msg),
-  false);
-
-window.addEventListener('compose-window-unload',
+addEventListener("load", Enigmail.msg.composeStartup.bind(Enigmail.msg), {
+  capture: false,
+  once: true,
+});
+
+window.addEventListener(
+  "unload-enigmail",
+  Enigmail.composeUnload.bind(Enigmail.msg)
+);
+
+window.addEventListener(
+  "compose-window-unload",
   Enigmail.msg.msgComposeClose.bind(Enigmail.msg),
-  true);
+  true
+);
--- a/mail/extensions/openpgp/content/ui/enigmailMsgHdrViewOverlay.js
+++ b/mail/extensions/openpgp/content/ui/enigmailMsgHdrViewOverlay.js
@@ -1,1310 +1,1718 @@
-/*global EnigmailWindows: false, EnigmailLocale: false, EnigmailPrefs: false, EnigmailTime: false */
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 "use strict";
 
 /* Globals from Thunderbird: */
 /* global gFolderDisplay: false, currentAttachments: false, gSMIMEContainer: false, gSignedUINode: false, gEncryptedUINode: false */
 /* global gDBView: false, msgWindow: false, messageHeaderSink: false, gMessageListeners: false, findEmailNodeFromPopupNode: true */
 /* global gExpandedHeaderView: false, CanDetachAttachments: true, gEncryptedURIService: false, FillAttachmentListPopup: false */
 /* global attachmentList: false, MailOfflineMgr: false, currentHeaderData: false, ContentTypeIsSMIME: false */
 
-var EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-var EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-var EnigmailVerify = ChromeUtils.import("chrome://openpgp/content/modules/mimeVerify.jsm").EnigmailVerify;
-var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-var EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-var EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-var EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-var EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-var EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-var EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-var EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-var EnigmailURIs = ChromeUtils.import("chrome://openpgp/content/modules/uris.jsm").EnigmailURIs;
-var EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-var EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-var EnigmailClipboard = ChromeUtils.import("chrome://openpgp/content/modules/clipboard.jsm").EnigmailClipboard;
-var EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-var EnigmailWks = ChromeUtils.import("chrome://openpgp/content/modules/webKey.jsm").EnigmailWks;
-var EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-var EnigmailMsgRead = ChromeUtils.import("chrome://openpgp/content/modules/msgRead.jsm").EnigmailMsgRead;
-var EnigmailSingletons = ChromeUtils.import("chrome://openpgp/content/modules/singletons.jsm").EnigmailSingletons;
-var EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
-var EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+var EnigmailCore = ChromeUtils.import(
+  "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+var EnigmailFuncs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+var EnigmailVerify = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mimeVerify.jsm"
+).EnigmailVerify;
+var EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm")
+  .EnigmailLog;
+var EnigmailPrefs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+var EnigmailLocale = ChromeUtils.import(
+  "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+var EnigmailWindows = ChromeUtils.import(
+  "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+var EnigmailDialog = ChromeUtils.import(
+  "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+var EnigmailTime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/time.jsm"
+).EnigmailTime;
+var EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm")
+  .EnigmailGpg;
+var EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm")
+  .EnigmailKey;
+var EnigmailKeyRing = ChromeUtils.import(
+  "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+var EnigmailURIs = ChromeUtils.import(
+  "chrome://openpgp/content/modules/uris.jsm"
+).EnigmailURIs;
+var EnigmailConstants = ChromeUtils.import(
+  "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+var EnigmailData = ChromeUtils.import(
+  "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+var EnigmailClipboard = ChromeUtils.import(
+  "chrome://openpgp/content/modules/clipboard.jsm"
+).EnigmailClipboard;
+var EnigmailStdlib = ChromeUtils.import(
+  "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+var EnigmailWks = ChromeUtils.import(
+  "chrome://openpgp/content/modules/webKey.jsm"
+).EnigmailWks;
+var EnigmailMime = ChromeUtils.import(
+  "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+var EnigmailMsgRead = ChromeUtils.import(
+  "chrome://openpgp/content/modules/msgRead.jsm"
+).EnigmailMsgRead;
+var EnigmailSingletons = ChromeUtils.import(
+  "chrome://openpgp/content/modules/singletons.jsm"
+).EnigmailSingletons;
+var EnigmailAutocrypt = ChromeUtils.import(
+  "chrome://openpgp/content/modules/autocrypt.jsm"
+).EnigmailAutocrypt;
+var EnigmailCompat = ChromeUtils.import(
+  "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
 
-if (!Enigmail) var Enigmail = {};
+if (!Enigmail) {
+  var Enigmail = {};
+}
 
 Enigmail.hdrView = {
-
   statusBar: null,
   enigmailBox: null,
   lastEncryptedMsgKey: null,
   lastEncryptedUri: null,
   flexbuttonAction: null,
 
-
-  hdrViewLoad: function() {
+  hdrViewLoad() {
     EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.hdrViewLoad\n");
 
     // THE FOLLOWING OVERRIDES CODE IN msgHdrViewOverlay.js
     // which wouldn't work otherwise
 
     this.origCanDetachAttachments = CanDetachAttachments;
     CanDetachAttachments = function() {
-      return Enigmail.hdrView.origCanDetachAttachments() && Enigmail.hdrView.enigCanDetachAttachments();
+      return (
+        Enigmail.hdrView.origCanDetachAttachments() &&
+        Enigmail.hdrView.enigCanDetachAttachments()
+      );
     };
 
     this.msgHdrViewLoad();
 
     // Override SMIME ui
     let signedHdrElement = document.getElementById("signedHdrIcon");
     if (signedHdrElement) {
-      signedHdrElement.setAttribute("onclick", "Enigmail.msg.viewSecurityInfo(event, true);");
+      signedHdrElement.setAttribute(
+        "onclick",
+        "Enigmail.msg.viewSecurityInfo(event, true);"
+      );
     }
 
     let encryptedHdrElement = document.getElementById("encryptedHdrIcon");
     if (encryptedHdrElement) {
-      encryptedHdrElement.setAttribute("onclick", "Enigmail.msg.viewSecurityInfo(event, true);");
+      encryptedHdrElement.setAttribute(
+        "onclick",
+        "Enigmail.msg.viewSecurityInfo(event, true);"
+      );
     }
 
     this.statusBar = document.getElementById("enigmail-status-bar");
     this.enigmailBox = document.getElementById("enigmailBox");
 
     let addrPopup = document.getElementById("emailAddressPopup");
     if (addrPopup) {
-      addrPopup.addEventListener("popupshowing", Enigmail.hdrView.displayAddressPopup.bind(addrPopup), false);
+      addrPopup.addEventListener(
+        "popupshowing",
+        Enigmail.hdrView.displayAddressPopup.bind(addrPopup)
+      );
     }
 
     // Thunderbird
     let attCtx = document.getElementById("attachmentItemContext");
     if (attCtx) {
-      attCtx.addEventListener("popupshowing", this.onShowAttachmentContextMenu.bind(Enigmail.hdrView), false);
+      attCtx.addEventListener(
+        "popupshowing",
+        this.onShowAttachmentContextMenu.bind(Enigmail.hdrView)
+      );
     }
   },
 
-  displayAddressPopup: function(event) {
+  displayAddressPopup(event) {
     let target = event.target;
-    EnigmailFuncs.collapseAdvanced(target, 'hidden');
+    EnigmailFuncs.collapseAdvanced(target, "hidden");
   },
 
-  statusBarHide: function() {
+  statusBarHide() {
     try {
       this.statusBar.removeAttribute("signed");
       this.statusBar.removeAttribute("encrypted");
       this.enigmailBox.setAttribute("collapsed", "true");
 
       Enigmail.msg.setAttachmentReveal(null);
       if (Enigmail.msg.securityInfo) {
         Enigmail.msg.securityInfo.statusFlags = 0;
         Enigmail.msg.securityInfo.msgSigned = 0;
         Enigmail.msg.securityInfo.msgEncrypted = 0;
       }
 
       let enigMsgPane = document.getElementById("enigmailMsgDisplay");
       let bodyElement = document.getElementById("messagepane");
       enigMsgPane.setAttribute("collapsed", true);
       bodyElement.removeAttribute("collapsed");
-    }
-    catch (ex) {}
+    } catch (ex) {}
   },
 
-  setStatusText: function(txt) {
+  setStatusText(txt) {
     let s = document.getElementById("enigmailStatusText");
     if (s) {
       s.firstChild.data = txt;
     }
   },
 
-  updateHdrIcons: function(exitCode, statusFlags, keyId, userId, sigDetails, errorMsg, blockSeparation, encToDetails, xtraStatus, encMimePartNumber) {
-    EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.updateHdrIcons: exitCode=" + exitCode + ", statusFlags=" + statusFlags + ", keyId=" + keyId + ", userId=" + userId + ", " + errorMsg +
-      "\n");
+  updateHdrIcons(
+    exitCode,
+    statusFlags,
+    keyId,
+    userId,
+    sigDetails,
+    errorMsg,
+    blockSeparation,
+    encToDetails,
+    xtraStatus,
+    encMimePartNumber
+  ) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgHdrViewOverlay.js: this.updateHdrIcons: exitCode=" +
+        exitCode +
+        ", statusFlags=" +
+        statusFlags +
+        ", keyId=" +
+        keyId +
+        ", userId=" +
+        userId +
+        ", " +
+        errorMsg +
+        "\n"
+    );
 
-    if (Enigmail.msg.securityInfo && Enigmail.msg.securityInfo.xtraStatus && Enigmail.msg.securityInfo.xtraStatus === "wks-request") {
+    if (
+      Enigmail.msg.securityInfo &&
+      Enigmail.msg.securityInfo.xtraStatus &&
+      Enigmail.msg.securityInfo.xtraStatus === "wks-request"
+    ) {
       return;
     }
 
     this.statusBar = document.getElementById("enigmail-status-bar");
     this.enigmailBox = document.getElementById("enigmailBox");
 
-    if (gFolderDisplay.selectedMessageUris && gFolderDisplay.selectedMessageUris.length > 0) {
+    if (
+      gFolderDisplay.selectedMessageUris &&
+      gFolderDisplay.selectedMessageUris.length > 0
+    ) {
       this.lastEncryptedMsgKey = gFolderDisplay.selectedMessageUris[0];
     }
 
-    if (!errorMsg)
+    if (!errorMsg) {
       errorMsg = "";
+    }
 
     var replaceUid = null;
     if (keyId && gFolderDisplay.selectedMessage) {
-      replaceUid = EnigmailMsgRead.matchUidToSender(keyId, gFolderDisplay.selectedMessage);
+      replaceUid = EnigmailMsgRead.matchUidToSender(
+        keyId,
+        gFolderDisplay.selectedMessage
+      );
     }
 
     if (!replaceUid) {
       replaceUid = userId.replace(/\n.*$/gm, "");
     }
 
-    if (Enigmail.msg.savedHeaders && "x-pgp-encoding-format" in Enigmail.msg.savedHeaders &&
-      (Enigmail.msg.savedHeaders["x-pgp-encoding-format"].search(/partitioned/i) === 0)) {
+    if (
+      Enigmail.msg.savedHeaders &&
+      "x-pgp-encoding-format" in Enigmail.msg.savedHeaders &&
+      Enigmail.msg.savedHeaders["x-pgp-encoding-format"].search(
+        /partitioned/i
+      ) === 0
+    ) {
       if (currentAttachments && currentAttachments.length) {
         Enigmail.msg.setAttachmentReveal(currentAttachments);
       }
     }
 
     if (userId && replaceUid) {
       // no EnigConvertGpgToUnicode() here; strings are already UTF-8
       replaceUid = replaceUid.replace(/\\[xe]3a/gi, ":");
       errorMsg = errorMsg.replace(userId, replaceUid);
     }
 
     var errorLines = "";
     var fullStatusInfo = "";
 
     if (exitCode == EnigmailConstants.POSSIBLE_PGPMIME) {
       exitCode = 0;
-    }
-    else {
-      if (errorMsg) {
-        // no EnigConvertGpgToUnicode() here; strings are already UTF-8
-        errorLines = errorMsg.split(/\r?\n/);
-        fullStatusInfo = errorMsg;
-      }
+    } else if (errorMsg) {
+      // no EnigConvertGpgToUnicode() here; strings are already UTF-8
+      errorLines = errorMsg.split(/\r?\n/);
+      fullStatusInfo = errorMsg;
     }
 
-    if (errorLines && (errorLines.length > 22)) {
+    if (errorLines && errorLines.length > 22) {
       // Retain only first twenty lines and last two lines of error message
-      var lastLines = errorLines[errorLines.length - 2] + "\n" +
-        errorLines[errorLines.length - 1] + "\n";
+      var lastLines =
+        errorLines[errorLines.length - 2] +
+        "\n" +
+        errorLines[errorLines.length - 1] +
+        "\n";
 
-      while (errorLines.length > 20)
+      while (errorLines.length > 20) {
         errorLines.pop();
+      }
 
       errorMsg = errorLines.join("\n") + "\n...\n" + lastLines;
     }
 
     var statusInfo = "";
     var statusLine = "";
     var statusArr = [];
 
     if (statusFlags & EnigmailConstants.NODATA) {
-      if (statusFlags & EnigmailConstants.PGP_MIME_SIGNED)
+      if (statusFlags & EnigmailConstants.PGP_MIME_SIGNED) {
         statusFlags |= EnigmailConstants.UNVERIFIED_SIGNATURE;
+      }
 
-      if (statusFlags & EnigmailConstants.PGP_MIME_ENCRYPTED)
+      if (statusFlags & EnigmailConstants.PGP_MIME_ENCRYPTED) {
         statusFlags |= EnigmailConstants.DECRYPTION_INCOMPLETE;
+      }
     }
 
     if (!(statusFlags & EnigmailConstants.PGP_MIME_ENCRYPTED)) {
       encMimePartNumber = "";
     }
 
     if (!EnigmailPrefs.getPref("displayPartiallySigned")) {
-      if ((statusFlags & (EnigmailConstants.PARTIALLY_PGP)) &&
-        (statusFlags & (EnigmailConstants.BAD_SIGNATURE))) {
-        statusFlags &= ~(EnigmailConstants.BAD_SIGNATURE | EnigmailConstants.PARTIALLY_PGP);
+      if (
+        statusFlags & EnigmailConstants.PARTIALLY_PGP &&
+        statusFlags & EnigmailConstants.BAD_SIGNATURE
+      ) {
+        statusFlags &= ~(
+          EnigmailConstants.BAD_SIGNATURE | EnigmailConstants.PARTIALLY_PGP
+        );
         if (statusFlags === 0) {
           errorMsg = "";
           fullStatusInfo = "";
         }
       }
     }
 
-    var msgSigned = (statusFlags & (EnigmailConstants.BAD_SIGNATURE |
-      EnigmailConstants.GOOD_SIGNATURE |
-      EnigmailConstants.EXPIRED_KEY_SIGNATURE |
-      EnigmailConstants.EXPIRED_SIGNATURE |
-      EnigmailConstants.UNVERIFIED_SIGNATURE |
-      EnigmailConstants.REVOKED_KEY |
-      EnigmailConstants.EXPIRED_KEY_SIGNATURE |
-      EnigmailConstants.EXPIRED_SIGNATURE));
-    var msgEncrypted = (statusFlags & (EnigmailConstants.DECRYPTION_OKAY |
-      EnigmailConstants.DECRYPTION_INCOMPLETE |
-      EnigmailConstants.DECRYPTION_FAILED));
+    var msgSigned =
+      statusFlags &
+      (EnigmailConstants.BAD_SIGNATURE |
+        EnigmailConstants.GOOD_SIGNATURE |
+        EnigmailConstants.EXPIRED_KEY_SIGNATURE |
+        EnigmailConstants.EXPIRED_SIGNATURE |
+        EnigmailConstants.UNVERIFIED_SIGNATURE |
+        EnigmailConstants.REVOKED_KEY |
+        EnigmailConstants.EXPIRED_KEY_SIGNATURE |
+        EnigmailConstants.EXPIRED_SIGNATURE);
+    var msgEncrypted =
+      statusFlags &
+      (EnigmailConstants.DECRYPTION_OKAY |
+        EnigmailConstants.DECRYPTION_INCOMPLETE |
+        EnigmailConstants.DECRYPTION_FAILED);
 
-    if (msgSigned && (statusFlags & EnigmailConstants.IMPORTED_KEY)) {
-      statusFlags &= (~EnigmailConstants.IMPORTED_KEY);
+    if (msgSigned && statusFlags & EnigmailConstants.IMPORTED_KEY) {
+      statusFlags &= ~EnigmailConstants.IMPORTED_KEY;
     }
 
-    if (!(statusFlags & EnigmailConstants.DECRYPTION_FAILED) &&
-      ((!(statusFlags & (EnigmailConstants.DECRYPTION_INCOMPLETE |
+    if (
+      !(statusFlags & EnigmailConstants.DECRYPTION_FAILED) &&
+      (!(
+        statusFlags &
+        (EnigmailConstants.DECRYPTION_INCOMPLETE |
           EnigmailConstants.UNVERIFIED_SIGNATURE |
           EnigmailConstants.DECRYPTION_FAILED |
-          EnigmailConstants.BAD_SIGNATURE))) ||
-        (statusFlags & EnigmailConstants.DISPLAY_MESSAGE) &&
-        !(statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE)) &&
-      !(statusFlags & EnigmailConstants.IMPORTED_KEY)) {
+          EnigmailConstants.BAD_SIGNATURE)
+      ) ||
+        (statusFlags & EnigmailConstants.DISPLAY_MESSAGE &&
+          !(statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE))) &&
+      !(statusFlags & EnigmailConstants.IMPORTED_KEY)
+    ) {
       // normal exit / display message
       statusLine = errorMsg;
       statusInfo = statusLine;
 
       if (sigDetails) {
         var detailArr = sigDetails.split(/ /);
 
         let dateTime = EnigmailTime.getDateTime(detailArr[2], true, true);
         var txt = EnigmailLocale.getString("keyAndSigDate", [keyId, dateTime]);
         statusArr.push(txt);
         statusInfo += "\n" + txt;
         var fpr = "";
         if (detailArr.length >= 10) {
           fpr = EnigmailKey.formatFpr(detailArr[9]);
-        }
-        else {
+        } else {
           fpr = EnigmailKey.formatFpr(detailArr[0]);
         }
         if (fpr) {
           statusInfo += "\n" + EnigmailLocale.getString("keyFpr", [fpr]);
         }
         if (detailArr.length > 7) {
           var signingAlg = EnigmailGpg.signingAlgIdToString(detailArr[6]);
           var hashAlg = EnigmailGpg.hashAlgIdToString(detailArr[7]);
 
-          statusInfo += "\n\n" + EnigmailLocale.getString("usedAlgorithms", [signingAlg, hashAlg]);
+          statusInfo +=
+            "\n\n" +
+            EnigmailLocale.getString("usedAlgorithms", [signingAlg, hashAlg]);
         }
       }
       fullStatusInfo = statusInfo;
-
-    }
-    else {
+    } else {
       // no normal exit / don't display message
       // - process failed decryptions first because they imply bad signature handling
       if (statusFlags & EnigmailConstants.BAD_PASSPHRASE) {
         statusInfo = EnigmailLocale.getString("badPhrase");
         statusLine = statusInfo + EnigmailLocale.getString("clickDecryptRetry");
-      }
-      else if (statusFlags & EnigmailConstants.DECRYPTION_FAILED) {
+      } else if (statusFlags & EnigmailConstants.DECRYPTION_FAILED) {
         if (statusFlags & EnigmailConstants.MISSING_MDC) {
           statusInfo = EnigmailLocale.getString("missingMdcError");
           statusLine = statusInfo;
-        }
-        else if (statusFlags & EnigmailConstants.MISSING_PASSPHRASE) {
+        } else if (statusFlags & EnigmailConstants.MISSING_PASSPHRASE) {
           statusInfo = EnigmailLocale.getString("missingPassphrase");
-          statusLine = statusInfo + EnigmailLocale.getString("clickDecryptRetry");
-        }
-        else if (statusFlags & EnigmailConstants.NO_SECKEY) {
+          statusLine =
+            statusInfo + EnigmailLocale.getString("clickDecryptRetry");
+        } else if (statusFlags & EnigmailConstants.NO_SECKEY) {
           statusInfo = EnigmailLocale.getString("needKey");
-        }
-        else {
+        } else {
           statusInfo = EnigmailLocale.getString("failedDecrypt");
         }
-        statusLine = statusInfo + EnigmailLocale.getString("clickDetailsButton");
-      }
-      else if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
+        statusLine =
+          statusInfo + EnigmailLocale.getString("clickDetailsButton");
+      } else if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
         statusInfo = EnigmailLocale.getString("unverifiedSig");
         if (keyId) {
-          statusLine = statusInfo + EnigmailLocale.getString("clickImportButton");
+          statusLine =
+            statusInfo + EnigmailLocale.getString("clickImportButton");
+        } else {
+          statusLine =
+            statusInfo + EnigmailLocale.getString("keyTypeUnsupported");
         }
-        else {
-          statusLine = statusInfo + EnigmailLocale.getString("keyTypeUnsupported");
-        }
-      }
-      else if (statusFlags & (EnigmailConstants.BAD_SIGNATURE |
+      } else if (
+        statusFlags &
+        (EnigmailConstants.BAD_SIGNATURE |
           EnigmailConstants.EXPIRED_SIGNATURE |
-          EnigmailConstants.EXPIRED_KEY_SIGNATURE)) {
+          EnigmailConstants.EXPIRED_KEY_SIGNATURE)
+      ) {
         statusInfo = EnigmailLocale.getString("unverifiedSig");
-        statusLine = statusInfo + EnigmailLocale.getString("clickDetailsButton");
-      }
-      else if (statusFlags & EnigmailConstants.DECRYPTION_INCOMPLETE) {
+        statusLine =
+          statusInfo + EnigmailLocale.getString("clickDetailsButton");
+      } else if (statusFlags & EnigmailConstants.DECRYPTION_INCOMPLETE) {
         statusInfo = EnigmailLocale.getString("incompleteDecrypt");
-        statusLine = statusInfo + EnigmailLocale.getString("clickDetailsButton");
-      }
-      else if (statusFlags & EnigmailConstants.IMPORTED_KEY) {
+        statusLine =
+          statusInfo + EnigmailLocale.getString("clickDetailsButton");
+      } else if (statusFlags & EnigmailConstants.IMPORTED_KEY) {
         statusLine = "";
         statusInfo = "";
         EnigmailDialog.info(window, errorMsg);
-      }
-      else {
+      } else {
         // TODO: can we ever get to this point anymore?
         // FIXME: the viewInfo string is outdated
         statusInfo = EnigmailLocale.getString("failedDecryptVerify");
         statusLine = statusInfo + EnigmailLocale.getString("viewInfo");
       }
       // add key infos if available
       if (keyId) {
         var si = EnigmailLocale.getString("unverifiedSig"); // "Unverified signature"
         if (statusInfo === "") {
           statusInfo += si;
           statusLine = si + EnigmailLocale.getString("clickDetailsButton");
         }
         if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
           statusInfo += "\n" + EnigmailLocale.getString("keyNeeded", [keyId]); // "public key ... needed"
-        }
-        else {
+        } else {
           statusInfo += "\n" + EnigmailLocale.getString("keyUsed", [keyId]); // "public key ... used"
         }
       }
       statusInfo += "\n\n" + errorMsg;
     }
 
-    if (statusFlags & EnigmailConstants.DECRYPTION_OKAY ||
-      (this.statusBar.getAttribute("encrypted") == "ok")) {
+    if (
+      statusFlags & EnigmailConstants.DECRYPTION_OKAY ||
+      this.statusBar.getAttribute("encrypted") == "ok"
+    ) {
       var statusMsg;
       if (xtraStatus && xtraStatus == "buggyMailFormat") {
         statusMsg = EnigmailLocale.getString("decryptedMsgWithFormatError");
-      }
-      else {
+      } else {
         statusMsg = EnigmailLocale.getString("decryptedMsg");
       }
       if (!statusInfo) {
         statusInfo = statusMsg;
-      }
-      else {
+      } else {
         statusInfo = statusMsg + "\n" + statusInfo;
       }
       if (!statusLine) {
         statusLine = statusInfo;
-      }
-      else {
+      } else {
         statusLine = statusMsg + "; " + statusLine;
       }
     }
 
     if (EnigmailPrefs.getPref("displayPartiallySigned")) {
       if (statusFlags & EnigmailConstants.PARTIALLY_PGP) {
         if (msgSigned && msgEncrypted) {
-          statusLine = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgSignedAndEnc")]);
+          statusLine = EnigmailLocale.getString("msgPart", [
+            EnigmailLocale.getString("msgSignedAndEnc"),
+          ]);
           statusLine += EnigmailLocale.getString("clickDetailsButton");
-          statusInfo = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgSigned")]) +
-            "\n" + statusInfo;
-        }
-        else if (msgEncrypted) {
-          statusLine = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgEncrypted")]);
+          statusInfo =
+            EnigmailLocale.getString("msgPart", [
+              EnigmailLocale.getString("msgSigned"),
+            ]) +
+            "\n" +
+            statusInfo;
+        } else if (msgEncrypted) {
+          statusLine = EnigmailLocale.getString("msgPart", [
+            EnigmailLocale.getString("msgEncrypted"),
+          ]);
           statusLine += EnigmailLocale.getString("clickDetailsButton");
-          statusInfo = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgEncrypted")]) +
-            "\n" + statusInfo;
-        }
-        else if (msgSigned) {
+          statusInfo =
+            EnigmailLocale.getString("msgPart", [
+              EnigmailLocale.getString("msgEncrypted"),
+            ]) +
+            "\n" +
+            statusInfo;
+        } else if (msgSigned) {
           if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
-            statusLine = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgSignedUnkownKey")]);
+            statusLine = EnigmailLocale.getString("msgPart", [
+              EnigmailLocale.getString("msgSignedUnkownKey"),
+            ]);
             if (keyId) {
               statusLine += EnigmailLocale.getString("clickImportButton");
-            }
-            else {
+            } else {
               statusLine += EnigmailLocale.getString("keyTypeUnsupported");
             }
-          }
-          else {
-            statusLine = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgSigned")]);
+          } else {
+            statusLine = EnigmailLocale.getString("msgPart", [
+              EnigmailLocale.getString("msgSigned"),
+            ]);
             statusLine += EnigmailLocale.getString("clickDetailsButton");
           }
-          statusInfo = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgSigned")]) +
-            "\n" + statusInfo;
+          statusInfo =
+            EnigmailLocale.getString("msgPart", [
+              EnigmailLocale.getString("msgSigned"),
+            ]) +
+            "\n" +
+            statusInfo;
         }
       }
     }
 
     // if we have parsed ENC_TO entries, add them as status info
     if (encToDetails && encToDetails.length > 0) {
-      statusInfo += "\n\n" + EnigmailLocale.getString("encryptKeysNote", [encToDetails]);
+      statusInfo +=
+        "\n\n" + EnigmailLocale.getString("encryptKeysNote", [encToDetails]);
     }
 
     if (xtraStatus === "process-manually") {
       let buttonLabel = "";
       if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
-        statusLine = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgSigned")]);
+        statusLine = EnigmailLocale.getString("msgPart", [
+          EnigmailLocale.getString("msgSigned"),
+        ]);
         statusLine += EnigmailLocale.getString("verifyManually");
         buttonLabel = EnigmailLocale.getString("headerView.button.verify");
-      }
-      else {
-        statusLine = EnigmailLocale.getString("msgPart", [EnigmailLocale.getString("msgEncrypted")]);
+      } else {
+        statusLine = EnigmailLocale.getString("msgPart", [
+          EnigmailLocale.getString("msgEncrypted"),
+        ]);
         statusLine += EnigmailLocale.getString("decryptManually");
         buttonLabel = EnigmailLocale.getString("headerView.button.decrypt");
       }
 
       Enigmail.msg.securityInfo = {};
       this.displayFlexAction(statusLine, buttonLabel, xtraStatus);
       return;
     }
 
     if (!statusLine) {
       return;
     }
 
     Enigmail.msg.securityInfo = {
-      statusFlags: statusFlags,
-      keyId: keyId,
-      userId: userId,
-      statusLine: statusLine,
-      msgSigned: msgSigned,
-      statusArr: statusArr,
-      statusInfo: statusInfo,
-      fullStatusInfo: fullStatusInfo,
-      blockSeparation: blockSeparation,
-      xtraStatus: xtraStatus,
-      encryptedMimePart: encMimePartNumber
+      statusFlags,
+      keyId,
+      userId,
+      statusLine,
+      msgSigned,
+      statusArr,
+      statusInfo,
+      fullStatusInfo,
+      blockSeparation,
+      xtraStatus,
+      encryptedMimePart: encMimePartNumber,
     };
 
     Enigmail.msg.createArtificialAutocryptHeader();
 
     if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
       this.tryImportAutocryptHeader();
     }
 
     this.displayStatusBar();
     this.updateMsgDb();
-
   },
 
   /**
    * Check whether we got a WKS request
    */
-  checkWksConfirmRequest: function(jsonStr) {
+  checkWksConfirmRequest(jsonStr) {
     let requestObj;
     try {
       requestObj = JSON.parse(jsonStr);
-    }
-    catch (ex) {
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: checkWksConfirmRequest parsing JSON failed\n");
+    } catch (ex) {
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: checkWksConfirmRequest parsing JSON failed\n"
+      );
       return;
     }
 
-    if ("type" in requestObj && requestObj.type.toLowerCase() === "confirmation-request") {
-      EnigmailWks.getWksClientPathAsync(window, function _res(wksClientPath) {
-        if (!wksClientPath) return;
+    if (
+      "type" in requestObj &&
+      requestObj.type.toLowerCase() === "confirmation-request"
+    ) {
+      EnigmailWks.getWksClientPathAsync(window, function(wksClientPath) {
+        if (!wksClientPath) {
+          return;
+        }
 
-        Enigmail.hdrView.displayFlexAction(EnigmailLocale.getString("wksConfirmationReq"),
-          EnigmailLocale.getString("wksConfirmationReq.button.label"), "wks-request");
+        Enigmail.hdrView.displayFlexAction(
+          EnigmailLocale.getString("wksConfirmationReq"),
+          EnigmailLocale.getString("wksConfirmationReq.button.label"),
+          "wks-request"
+        );
         Enigmail.hdrView.displayWksMessage();
       });
-    }
-    else {
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: checkWksConfirmRequest failed condition\n");
+    } else {
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: checkWksConfirmRequest failed condition\n"
+      );
     }
   },
 
   /**
    * Display Enigmail header with text and specific button
    *
    * @param {String} hdrMessage: Message to be displayed in header
    * @param {String} buttonLabel: Label of button
    * @param {String} requestType: action to be performed
    */
-  displayFlexAction: function(hdrMessage, buttonLabel, requestType) {
+  displayFlexAction(hdrMessage, buttonLabel, requestType) {
     if (!Enigmail.msg.securityInfo) {
       Enigmail.msg.securityInfo = {};
     }
     Enigmail.msg.securityInfo.xtraStatus = requestType;
     Enigmail.msg.securityInfo.statusInfo = hdrMessage;
 
     // Thunderbird
     this.setStatusText(hdrMessage);
     this.enigmailBox.removeAttribute("collapsed");
     let button = document.getElementById("enigmail_flexActionButton");
     button.setAttribute("label", buttonLabel);
     button.removeAttribute("hidden");
-    document.getElementById("enigmail_importKey").setAttribute("hidden", "true");
+    document
+      .getElementById("enigmail_importKey")
+      .setAttribute("hidden", "true");
 
-    this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown");
+    this.enigmailBox.setAttribute(
+      "class",
+      "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown"
+    );
   },
 
   /**
    * Display a localized message in lieu of the original message text
    */
-  displayWksMessage: function() {
+  displayWksMessage() {
     EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: displayWksMessage()\n");
 
     if (Enigmail.msg.securityInfo.xtraStatus === "wks-request") {
-
       let enigMsgPane = document.getElementById("enigmailMsgDisplay");
       let bodyElement = document.getElementById("messagepane");
       bodyElement.setAttribute("collapsed", true);
       enigMsgPane.removeAttribute("collapsed");
-      enigMsgPane.textContent = EnigmailLocale.getString("wksConfirmationReq.message");
+      enigMsgPane.textContent = EnigmailLocale.getString(
+        "wksConfirmationReq.message"
+      );
     }
   },
 
   /**
    * Try to import an autocrypt header from an unverified signature
    * (i.e. the sender's key is not available)
    */
-  tryImportAutocryptHeader: function() {
-    EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: tryImportAutocryptHeader()\n");
+  tryImportAutocryptHeader() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgHdrViewOverlay.js: tryImportAutocryptHeader()\n"
+    );
 
-    if (!("autocrypt" in currentHeaderData)) return;
-    if (!Enigmail.msg.isAutocryptEnabled()) return;
-    if (!("from" in currentHeaderData)) return;
+    if (!("autocrypt" in currentHeaderData)) {
+      return;
+    }
+    if (!Enigmail.msg.isAutocryptEnabled()) {
+      return;
+    }
+    if (!("from" in currentHeaderData)) {
+      return;
+    }
 
     let fromEmail = "";
     try {
-      fromEmail = EnigmailFuncs.stripEmail(currentHeaderData.from.headerValue).toLowerCase();
-    }
-    catch (ex) {}
+      fromEmail = EnigmailFuncs.stripEmail(
+        currentHeaderData.from.headerValue
+      ).toLowerCase();
+    } catch (ex) {}
 
     let keys = EnigmailKeyRing.getKeysByUserId(fromEmail, true);
-    if (keys.length > 0) return;
+    if (keys.length > 0) {
+      return;
+    }
 
     EnigmailAutocrypt.importAutocryptKeys([fromEmail]).then(foundKeys => {
-      EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: tryImportAutocryptHeader: got " +
-        foundKeys.length + " autocrypt keys\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgComposeOverlay.js: tryImportAutocryptHeader: got " +
+          foundKeys.length +
+          " autocrypt keys\n"
+      );
       if (foundKeys.length > 0) {
         let k = EnigmailKeyRing.getKeyById(Enigmail.msg.securityInfo.keyId);
-        if (k) gDBView.reloadMessageWithAllParts();
+        if (k) {
+          gDBView.reloadMessageWithAllParts();
+        }
       }
     });
   },
 
   /**
    * Display the Enigmail status bar and ask for handling the Setup Message
    */
-  displayAutoCryptSetupMsgHeader: function() {
-    Enigmail.hdrView.displayFlexAction(EnigmailLocale.getString("autocryptSetupReq"),
-      EnigmailLocale.getString("autocryptSetupReq.button.label"), "autocrypt-setup");
+  displayAutoCryptSetupMsgHeader() {
+    Enigmail.hdrView.displayFlexAction(
+      EnigmailLocale.getString("autocryptSetupReq"),
+      EnigmailLocale.getString("autocryptSetupReq.button.label"),
+      "autocrypt-setup"
+    );
     //view.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown");
     this.displayAutocryptMessage(true);
   },
 
-  displayAutocryptMessage: function(allowImport) {
-    EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: displayAutocryptMessage()\n");
+  displayAutocryptMessage(allowImport) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgHdrViewOverlay.js: displayAutocryptMessage()\n"
+    );
   },
 
-  displayStatusBar: function() {
-    let statusText = document.getElementById("enigmailStatusText");
+  displayStatusBar() {
+    //let statusText = document.getElementById("enigmailStatusText");
     let expStatusText = document.getElementById("expandedEnigmailStatusText");
     let icon = document.getElementById("enigToggleHeaderView2");
     let bodyElement = document.getElementById("messagepanebox");
 
     let secInfo = Enigmail.msg.securityInfo;
     let statusFlags = secInfo.statusFlags;
     let sMimeContainer, encryptedUINode, signedUINode;
 
     if (secInfo.statusArr.length > 0) {
       expStatusText.value = secInfo.statusArr[0];
       expStatusText.setAttribute("state", "true");
       icon.removeAttribute("collapsed");
-    }
-    else {
+    } else {
       expStatusText.value = "";
       expStatusText.setAttribute("state", "false");
       icon.setAttribute("collapsed", "true");
     }
 
     if (secInfo.statusLine) {
       this.setStatusText(secInfo.statusLine + " ");
       this.enigmailBox.removeAttribute("collapsed");
       this.displayExtendedStatus(true);
 
-      if ((secInfo.keyId && (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE)) ||
-        (statusFlags & EnigmailConstants.INLINE_KEY)) {
+      if (
+        (secInfo.keyId &&
+          statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) ||
+        statusFlags & EnigmailConstants.INLINE_KEY
+      ) {
         document.getElementById("enigmail_importKey").removeAttribute("hidden");
+      } else {
+        document
+          .getElementById("enigmail_importKey")
+          .setAttribute("hidden", "true");
       }
-      else {
-        document.getElementById("enigmail_importKey").setAttribute("hidden", "true");
-      }
-      document.getElementById("enigmail_flexActionButton").setAttribute("hidden", "true");
-    }
-    else {
+      document
+        .getElementById("enigmail_flexActionButton")
+        .setAttribute("hidden", "true");
+    } else {
       this.setStatusText("");
       this.enigmailBox.setAttribute("collapsed", "true");
       this.displayExtendedStatus(false);
     }
 
     sMimeContainer = gSMIMEContainer;
     signedUINode = gSignedUINode;
     encryptedUINode = gEncryptedUINode;
 
     /* eslint block-scoped-var: 0*/
-    if (typeof(sMimeContainer) !== "object")
+    if (typeof sMimeContainer !== "object") {
       return;
-    if (!sMimeContainer)
+    }
+    if (!sMimeContainer) {
       return;
+    }
 
     // Update icons and header-box css-class
     try {
       sMimeContainer.collapsed = false;
       signedUINode.collapsed = false;
       encryptedUINode.collapsed = false;
 
-      if ((statusFlags & EnigmailConstants.BAD_SIGNATURE) &&
-        !(statusFlags & EnigmailConstants.GOOD_SIGNATURE)) {
+      if (
+        statusFlags & EnigmailConstants.BAD_SIGNATURE &&
+        !(statusFlags & EnigmailConstants.GOOD_SIGNATURE)
+      ) {
         // Display untrusted/bad signature icon
         signedUINode.setAttribute("signed", "unknown");
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown");
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown"
+        );
         this.statusBar.setAttribute("signed", "unknown");
-      }
-      else if ((statusFlags & EnigmailConstants.GOOD_SIGNATURE) &&
-        (statusFlags & EnigmailConstants.TRUSTED_IDENTITY) &&
-        !(statusFlags & (EnigmailConstants.REVOKED_KEY |
-          EnigmailConstants.EXPIRED_KEY_SIGNATURE |
-          EnigmailConstants.EXPIRED_SIGNATURE))) {
+      } else if (
+        statusFlags & EnigmailConstants.GOOD_SIGNATURE &&
+        statusFlags & EnigmailConstants.TRUSTED_IDENTITY &&
+        !(
+          statusFlags &
+          (EnigmailConstants.REVOKED_KEY |
+            EnigmailConstants.EXPIRED_KEY_SIGNATURE |
+            EnigmailConstants.EXPIRED_SIGNATURE)
+        )
+      ) {
         // Display trusted good signature icon
         signedUINode.setAttribute("signed", "ok");
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureOk");
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelSignatureOk"
+        );
         this.statusBar.setAttribute("signed", "ok");
         bodyElement.setAttribute("enigSigned", "ok");
-      }
-      else if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
+      } else if (statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
         // Display unverified signature icon
         signedUINode.setAttribute("signed", "unknown");
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown");
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown"
+        );
         this.statusBar.setAttribute("signed", "unknown");
-      }
-      else if (statusFlags & (EnigmailConstants.REVOKED_KEY |
+      } else if (
+        statusFlags &
+        (EnigmailConstants.REVOKED_KEY |
           EnigmailConstants.EXPIRED_KEY_SIGNATURE |
           EnigmailConstants.EXPIRED_SIGNATURE |
-          EnigmailConstants.GOOD_SIGNATURE)) {
+          EnigmailConstants.GOOD_SIGNATURE)
+      ) {
         // Display unverified signature icon
         signedUINode.setAttribute("signed", "unknown");
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureVerified");
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelSignatureVerified"
+        );
         this.statusBar.setAttribute("signed", "unknown");
-      }
-      else if (statusFlags & EnigmailConstants.INLINE_KEY) {
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown");
-      }
-      else {
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelNoSignature");
+      } else if (statusFlags & EnigmailConstants.INLINE_KEY) {
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelSignatureUnknown"
+        );
+      } else {
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelNoSignature"
+        );
       }
 
       if (statusFlags & EnigmailConstants.DECRYPTION_OKAY) {
         EnigmailURIs.rememberEncryptedUri(this.lastEncryptedMsgKey);
 
         // Display encrypted icon
         encryptedUINode.setAttribute("encrypted", "ok");
         this.statusBar.setAttribute("encrypted", "ok");
-      }
-      else if (statusFlags &
-        (EnigmailConstants.DECRYPTION_INCOMPLETE | EnigmailConstants.DECRYPTION_FAILED)) {
+      } else if (
+        statusFlags &
+        (EnigmailConstants.DECRYPTION_INCOMPLETE |
+          EnigmailConstants.DECRYPTION_FAILED)
+      ) {
         // Display un-encrypted icon
         encryptedUINode.setAttribute("encrypted", "notok");
         this.statusBar.setAttribute("encrypted", "notok");
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureNotOk");
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelSignatureNotOk"
+        );
       }
 
       // special handling after trying to fix buggy mail format (see buggyExchangeEmailContent in code)
       if (secInfo.xtraStatus && secInfo.xtraStatus == "buggyMailFormat") {
-        this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelBuggyMailFormat");
+        this.enigmailBox.setAttribute(
+          "class",
+          "expandedEnigmailBox enigmailHeaderBoxLabelBuggyMailFormat"
+        );
       }
-    }
-    catch (ex) {
+    } catch (ex) {
       EnigmailLog.writeException("displayStatusBar", ex);
     }
   },
 
-  dispSecurityContext: function() {
-
+  dispSecurityContext() {
     try {
       if (Enigmail.msg.securityInfo) {
-        if ((Enigmail.msg.securityInfo.statusFlags & EnigmailConstants.NODATA) &&
-          (Enigmail.msg.securityInfo.statusFlags &
-            (EnigmailConstants.PGP_MIME_SIGNED | EnigmailConstants.PGP_MIME_ENCRYPTED))) {
-          document.getElementById("enigmail_reloadMessage").removeAttribute("hidden");
-        }
-        else {
-          document.getElementById("enigmail_reloadMessage").setAttribute("hidden", "true");
+        if (
+          Enigmail.msg.securityInfo.statusFlags & EnigmailConstants.NODATA &&
+          Enigmail.msg.securityInfo.statusFlags &
+            (EnigmailConstants.PGP_MIME_SIGNED |
+              EnigmailConstants.PGP_MIME_ENCRYPTED)
+        ) {
+          document
+            .getElementById("enigmail_reloadMessage")
+            .removeAttribute("hidden");
+        } else {
+          document
+            .getElementById("enigmail_reloadMessage")
+            .setAttribute("hidden", "true");
         }
       }
 
       var optList = ["pgpSecurityInfo", "copySecurityInfo"];
       for (var j = 0; j < optList.length; j++) {
         var menuElement = document.getElementById("enigmail_" + optList[j]);
         if (Enigmail.msg.securityInfo) {
           menuElement.removeAttribute("disabled");
-        }
-        else {
+        } else {
           menuElement.setAttribute("disabled", "true");
         }
       }
 
-      this.setSenderStatus("signSenderKey", "editSenderKeyTrust", "showPhoto", "dispKeyDetails");
-    }
-    catch (ex) {
-      EnigmailLog.ERROR("error on displaying Security menu:\n" + ex.toString() + "\n");
+      this.setSenderStatus(
+        "signSenderKey",
+        "editSenderKeyTrust",
+        "showPhoto",
+        "dispKeyDetails"
+      );
+    } catch (ex) {
+      EnigmailLog.ERROR(
+        "error on displaying Security menu:\n" + ex.toString() + "\n"
+      );
     }
   },
 
-
-  updateSendersKeyMenu: function() {
-    this.setSenderStatus("keyMgmtSignKey",
+  updateSendersKeyMenu() {
+    this.setSenderStatus(
+      "keyMgmtSignKey",
       "keyMgmtKeyTrust",
       "keyMgmtShowPhoto",
       "keyMgmtDispKeyDetails",
-      "importpublickey");
+      "importpublickey"
+    );
   },
 
-  setSenderStatus: function(elemSign, elemTrust, elemPhoto, elemKeyProps, elemImportKey) {
-
+  setSenderStatus(elemSign, elemTrust, elemPhoto, elemKeyProps, elemImportKey) {
     function setElemStatus(elemName, disabledValue) {
-      document.getElementById("enigmail_" + elemName).setAttribute("disabled", !disabledValue);
+      document
+        .getElementById("enigmail_" + elemName)
+        .setAttribute("disabled", !disabledValue);
 
       let secondElem = document.getElementById("enigmail_" + elemName + "2");
-      if (secondElem) secondElem.setAttribute("disabled", !disabledValue);
+      if (secondElem) {
+        secondElem.setAttribute("disabled", !disabledValue);
+      }
     }
 
     var photo = false;
     var sign = false;
     var trust = false;
     var unknown = false;
     var signedMsg = false;
     var keyObj = null;
 
     if (Enigmail.msg.securityInfo) {
-      if (Enigmail.msg.securityInfo.statusFlags & EnigmailConstants.PHOTO_AVAILABLE) {
+      if (
+        Enigmail.msg.securityInfo.statusFlags &
+        EnigmailConstants.PHOTO_AVAILABLE
+      ) {
         photo = true;
       }
       if (Enigmail.msg.securityInfo.keyId) {
         keyObj = EnigmailKeyRing.getKeyById(Enigmail.msg.securityInfo.keyId);
       }
       if (Enigmail.msg.securityInfo.msgSigned) {
         signedMsg = true;
-        if (!(Enigmail.msg.securityInfo.statusFlags &
-            (EnigmailConstants.REVOKED_KEY | EnigmailConstants.EXPIRED_KEY_SIGNATURE | EnigmailConstants.UNVERIFIED_SIGNATURE))) {
+        if (
+          !(
+            Enigmail.msg.securityInfo.statusFlags &
+            (EnigmailConstants.REVOKED_KEY |
+              EnigmailConstants.EXPIRED_KEY_SIGNATURE |
+              EnigmailConstants.UNVERIFIED_SIGNATURE)
+          )
+        ) {
           sign = true;
         }
         if (keyObj && keyObj.isOwnerTrustUseful()) {
           trust = true;
         }
 
-        if (Enigmail.msg.securityInfo.statusFlags & EnigmailConstants.UNVERIFIED_SIGNATURE) {
+        if (
+          Enigmail.msg.securityInfo.statusFlags &
+          EnigmailConstants.UNVERIFIED_SIGNATURE
+        ) {
           unknown = true;
         }
       }
     }
 
-    if (elemTrust) setElemStatus(elemTrust, trust);
-    if (elemSign) setElemStatus(elemSign, sign);
-    if (elemPhoto) setElemStatus(elemPhoto, photo);
-    if (elemKeyProps) setElemStatus(elemKeyProps, (signedMsg && !unknown));
-    if (elemImportKey) setElemStatus(elemImportKey, unknown);
+    if (elemTrust) {
+      setElemStatus(elemTrust, trust);
+    }
+    if (elemSign) {
+      setElemStatus(elemSign, sign);
+    }
+    if (elemPhoto) {
+      setElemStatus(elemPhoto, photo);
+    }
+    if (elemKeyProps) {
+      setElemStatus(elemKeyProps, signedMsg && !unknown);
+    }
+    if (elemImportKey) {
+      setElemStatus(elemImportKey, unknown);
+    }
   },
 
-  editKeyExpiry: function() {
-    EnigmailWindows.editKeyExpiry(window, [Enigmail.msg.securityInfo.userId], [Enigmail.msg.securityInfo.keyId]);
+  editKeyExpiry() {
+    EnigmailWindows.editKeyExpiry(
+      window,
+      [Enigmail.msg.securityInfo.userId],
+      [Enigmail.msg.securityInfo.keyId]
+    );
     gDBView.reloadMessageWithAllParts();
   },
 
-  editKeyTrust: function() {
-    let enigmailSvc = EnigmailCore.getService();
+  editKeyTrust() {
     let key = EnigmailKeyRing.getKeyById(Enigmail.msg.securityInfo.keyId);
 
-    EnigmailWindows.editKeyTrust(window, [Enigmail.msg.securityInfo.userId], [key.keyId]);
+    EnigmailWindows.editKeyTrust(
+      window,
+      [Enigmail.msg.securityInfo.userId],
+      [key.keyId]
+    );
     gDBView.reloadMessageWithAllParts();
   },
 
-  signKey: function() {
-    let enigmailSvc = EnigmailCore.getService();
+  signKey() {
     let key = EnigmailKeyRing.getKeyById(Enigmail.msg.securityInfo.keyId);
 
-    EnigmailWindows.signKey(window, Enigmail.msg.securityInfo.userId, key.keyId, null);
+    EnigmailWindows.signKey(
+      window,
+      Enigmail.msg.securityInfo.userId,
+      key.keyId,
+      null
+    );
     gDBView.reloadMessageWithAllParts();
   },
 
-  msgHdrViewLoad: function() {
+  msgHdrViewLoad() {
     EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.msgHdrViewLoad\n");
 
     this.messageListener = {
       enigmailBox: document.getElementById("enigmailBox"),
-      onStartHeaders: function _listener_onStartHeaders() {
-        EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: _listener_onStartHeaders\n");
+      onStartHeaders() {
+        EnigmailLog.DEBUG(
+          "enigmailMsgHdrViewOverlay.js: _listener_onStartHeaders\n"
+        );
 
         try {
-
           Enigmail.hdrView.statusBarHide();
-          EnigmailVerify.setMsgWindow(msgWindow, Enigmail.msg.getCurrentMsgUriSpec());
+          EnigmailVerify.setMsgWindow(
+            msgWindow,
+            Enigmail.msg.getCurrentMsgUriSpec()
+          );
           Enigmail.hdrView.setStatusText("");
-          this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureOk");
+          this.enigmailBox.setAttribute(
+            "class",
+            "expandedEnigmailBox enigmailHeaderBoxLabelSignatureOk"
+          );
 
           let msgFrame = EnigmailWindows.getFrame(window, "messagepane");
           if (!msgFrame) {
             // TB >= 69
-            msgFrame = document.getElementById('messagepane').contentDocument;
+            msgFrame = document.getElementById("messagepane").contentDocument;
           }
 
           if (msgFrame) {
-            msgFrame.addEventListener("unload", Enigmail.hdrView.messageUnload.bind(Enigmail.hdrView), true);
-            msgFrame.addEventListener("load", Enigmail.hdrView.messageLoad.bind(Enigmail.hdrView), true);
+            msgFrame.addEventListener(
+              "unload",
+              Enigmail.hdrView.messageUnload.bind(Enigmail.hdrView),
+              true
+            );
+            msgFrame.addEventListener(
+              "load",
+              Enigmail.hdrView.messageLoad.bind(Enigmail.hdrView),
+              true
+            );
           }
 
           Enigmail.hdrView.forgetEncryptedMsgKey();
           Enigmail.hdrView.setWindowCallback();
-        }
-        catch (ex) {}
+        } catch (ex) {}
       },
 
-      onEndHeaders: function _listener_onEndHeaders() {
-        EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: _listener_onEndHeaders\n");
+      onEndHeaders() {
+        EnigmailLog.DEBUG(
+          "enigmailMsgHdrViewOverlay.js: _listener_onEndHeaders\n"
+        );
 
         try {
           Enigmail.hdrView.statusBarHide();
 
-          this.enigmailBox.setAttribute("class", "expandedEnigmailBox enigmailHeaderBoxLabelSignatureOk");
-        }
-        catch (ex) {}
+          this.enigmailBox.setAttribute(
+            "class",
+            "expandedEnigmailBox enigmailHeaderBoxLabelSignatureOk"
+          );
+        } catch (ex) {}
       },
 
-      beforeStartHeaders: function _listener_beforeStartHeaders() {
+      beforeStartHeaders() {
         return true;
-      }
+      },
     };
 
     gMessageListeners.push(this.messageListener);
 
     // fire the handlers since some windows open directly with a visible message
     this.messageListener.onStartHeaders();
     this.messageListener.onEndHeaders();
   },
 
-  messageUnload: function(event) {
+  messageUnload(event) {
     EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.messageUnload\n");
     if (Enigmail.hdrView.flexbuttonAction === null) {
       if (Enigmail.msg.securityInfo && Enigmail.msg.securityInfo.xtraStatus) {
         Enigmail.msg.securityInfo.xtraStatus = "";
       }
       this.forgetEncryptedMsgKey();
     }
   },
 
-  messageLoad: function(event) {
+  messageLoad(event) {
     EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.messageLoad\n");
 
     Enigmail.msg.messageAutoDecrypt();
     Enigmail.msg.handleAttchmentEvent();
   },
 
-  copyStatusInfo: function() {
+  copyStatusInfo() {
     if (Enigmail.msg.securityInfo) {
-      EnigmailClipboard.setClipboardContent(Enigmail.msg.securityInfo.statusInfo);
+      EnigmailClipboard.setClipboardContent(
+        Enigmail.msg.securityInfo.statusInfo
+      );
     }
   },
 
-  showPhoto: function() {
-    if (!Enigmail.msg.securityInfo) return;
+  showPhoto() {
+    if (!Enigmail.msg.securityInfo) {
+      return;
+    }
 
-    let enigmailSvc = EnigmailCore.getService();
     let key = EnigmailKeyRing.getKeyById(Enigmail.msg.securityInfo.keyId);
 
-    EnigmailWindows.showPhoto(window, key.keyId, Enigmail.msg.securityInfo.userId);
+    EnigmailWindows.showPhoto(
+      window,
+      key.keyId,
+      Enigmail.msg.securityInfo.userId
+    );
   },
 
+  dispKeyDetails() {
+    if (!Enigmail.msg.securityInfo) {
+      return;
+    }
 
-  dispKeyDetails: function() {
-    if (!Enigmail.msg.securityInfo) return;
-
-    let enigmailSvc = EnigmailCore.getService();
     let key = EnigmailKeyRing.getKeyById(Enigmail.msg.securityInfo.keyId);
 
     EnigmailWindows.openKeyDetails(window, key.keyId, false);
   },
 
-  createRuleFromAddress: function(emailAddressNode) {
+  createRuleFromAddress(emailAddressNode) {
     if (emailAddressNode) {
-      if (typeof(findEmailNodeFromPopupNode) == "function") {
-        emailAddressNode = findEmailNodeFromPopupNode(emailAddressNode, 'emailAddressPopup');
+      if (typeof findEmailNodeFromPopupNode == "function") {
+        emailAddressNode = findEmailNodeFromPopupNode(
+          emailAddressNode,
+          "emailAddressPopup"
+        );
       }
-      EnigmailWindows.createNewRule(window, emailAddressNode.getAttribute("emailAddress"));
+      EnigmailWindows.createNewRule(
+        window,
+        emailAddressNode.getAttribute("emailAddress")
+      );
     }
   },
 
-  forgetEncryptedMsgKey: function() {
+  forgetEncryptedMsgKey() {
     if (Enigmail.hdrView.lastEncryptedMsgKey) {
       EnigmailURIs.forgetEncryptedUri(Enigmail.hdrView.lastEncryptedMsgKey);
       Enigmail.hdrView.lastEncryptedMsgKey = null;
     }
 
     if (Enigmail.hdrView.lastEncryptedUri && gEncryptedURIService) {
       gEncryptedURIService.forgetEncrypted(Enigmail.hdrView.lastEncryptedUri);
       Enigmail.hdrView.lastEncryptedUri = null;
     }
   },
 
-  displayExtendedStatus: function(displayOn) {
+  displayExtendedStatus(displayOn) {
     var expStatusText = document.getElementById("expandedEnigmailStatusText");
     if (displayOn && expStatusText.getAttribute("state") == "true") {
       if (expStatusText.getAttribute("display") == "true") {
         expStatusText.removeAttribute("collapsed");
-      }
-      else {
+      } else {
         expStatusText.setAttribute("collapsed", "true");
       }
-    }
-    else {
+    } else {
       expStatusText.setAttribute("collapsed", "true");
     }
   },
 
-  toggleHeaderView: function() {
+  toggleHeaderView() {
     var viewToggle = document.getElementById("enigToggleHeaderView2");
     var expandedText = document.getElementById("expandedEnigmailStatusText");
     var state = viewToggle.getAttribute("state");
 
     if (state == "true") {
       viewToggle.setAttribute("state", "false");
       viewToggle.setAttribute("class", "enigmailExpandViewButton");
       expandedText.setAttribute("display", "false");
       this.displayExtendedStatus(false);
-    }
-    else {
+    } else {
       viewToggle.setAttribute("state", "true");
       viewToggle.setAttribute("class", "enigmailCollapseViewButton");
       expandedText.setAttribute("display", "true");
       this.displayExtendedStatus(true);
     }
   },
 
-  onShowAttachmentContextMenu: function(event) {
-    EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.onShowAttachmentContextMenu\n");
+  onShowAttachmentContextMenu(event) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgHdrViewOverlay.js: this.onShowAttachmentContextMenu\n"
+    );
 
     let contextMenu, selectedAttachments;
     // Thunderbird
-    contextMenu = document.getElementById('attachmentItemContext');
+    contextMenu = document.getElementById("attachmentItemContext");
     selectedAttachments = contextMenu.attachments;
 
-    var decryptOpenMenu = document.getElementById('enigmail_ctxDecryptOpen');
-    var decryptSaveMenu = document.getElementById('enigmail_ctxDecryptSave');
-    var importMenu = document.getElementById('enigmail_ctxImportKey');
-    var verifyMenu = document.getElementById('enigmail_ctxVerifyAtt');
+    var decryptOpenMenu = document.getElementById("enigmail_ctxDecryptOpen");
+    var decryptSaveMenu = document.getElementById("enigmail_ctxDecryptSave");
+    var importMenu = document.getElementById("enigmail_ctxImportKey");
+    var verifyMenu = document.getElementById("enigmail_ctxVerifyAtt");
 
     if (selectedAttachments.length > 0) {
-      this.enableContextMenuEntries(selectedAttachments[0], decryptOpenMenu, decryptSaveMenu, importMenu, verifyMenu);
-    }
-    else {
-      openMenu.setAttribute('disabled', true); /* global openMenu: false */
-      saveMenu.setAttribute('disabled', true); /* global saveMenu: false */
-      decryptOpenMenu.setAttribute('disabled', true);
-      decryptSaveMenu.setAttribute('disabled', true);
-      importMenu.setAttribute('disabled', true);
-      verifyMenu.setAttribute('disabled', true);
+      this.enableContextMenuEntries(
+        selectedAttachments[0],
+        decryptOpenMenu,
+        decryptSaveMenu,
+        importMenu,
+        verifyMenu
+      );
+    } else {
+      openMenu.setAttribute("disabled", true); /* global openMenu: false */
+      saveMenu.setAttribute("disabled", true); /* global saveMenu: false */
+      decryptOpenMenu.setAttribute("disabled", true);
+      decryptSaveMenu.setAttribute("disabled", true);
+      importMenu.setAttribute("disabled", true);
+      verifyMenu.setAttribute("disabled", true);
     }
   },
 
-  enableContextMenuEntries: function(attachment, decryptOpenMenu, decryptSaveMenu, importMenu, verifyMenu) {
+  enableContextMenuEntries(
+    attachment,
+    decryptOpenMenu,
+    decryptSaveMenu,
+    importMenu,
+    verifyMenu
+  ) {
     if (attachment.contentType.search(/^application\/pgp-keys/i) === 0) {
-      importMenu.removeAttribute('disabled');
-      decryptOpenMenu.setAttribute('disabled', true);
-      decryptSaveMenu.setAttribute('disabled', true);
-      verifyMenu.setAttribute('disabled', true);
-    }
-    else if (Enigmail.msg.checkEncryptedAttach(attachment)) {
-      if ((typeof(attachment.name) !== 'undefined' && attachment.name.match(/\.asc\.(gpg|pgp)$/i)) ||
-        (typeof(attachment.displayName) !== 'undefined' && attachment.displayName.match(/\.asc\.(gpg|pgp)$/i))) {
-        importMenu.removeAttribute('disabled');
+      importMenu.removeAttribute("disabled");
+      decryptOpenMenu.setAttribute("disabled", true);
+      decryptSaveMenu.setAttribute("disabled", true);
+      verifyMenu.setAttribute("disabled", true);
+    } else if (Enigmail.msg.checkEncryptedAttach(attachment)) {
+      if (
+        (typeof attachment.name !== "undefined" &&
+          attachment.name.match(/\.asc\.(gpg|pgp)$/i)) ||
+        (typeof attachment.displayName !== "undefined" &&
+          attachment.displayName.match(/\.asc\.(gpg|pgp)$/i))
+      ) {
+        importMenu.removeAttribute("disabled");
+      } else {
+        importMenu.setAttribute("disabled", true);
       }
-      else {
-        importMenu.setAttribute('disabled', true);
+      decryptOpenMenu.removeAttribute("disabled");
+      decryptSaveMenu.removeAttribute("disabled");
+      if (
+        EnigmailMsgRead.checkSignedAttachment(
+          attachment,
+          null,
+          currentAttachments
+        )
+      ) {
+        verifyMenu.removeAttribute("disabled");
+      } else {
+        verifyMenu.setAttribute("disabled", true);
       }
-      decryptOpenMenu.removeAttribute('disabled');
-      decryptSaveMenu.removeAttribute('disabled');
-      if (EnigmailMsgRead.checkSignedAttachment(attachment, null, currentAttachments)) {
-        verifyMenu.removeAttribute('disabled');
-      }
-      else {
-        verifyMenu.setAttribute('disabled', true);
-      }
-      if (typeof(attachment.displayName) == "undefined") {
+      if (typeof attachment.displayName == "undefined") {
         if (!attachment.name) {
           attachment.name = "message.pgp";
         }
-      }
-      else if (!attachment.displayName) {
+      } else if (!attachment.displayName) {
         attachment.displayName = "message.pgp";
       }
-    }
-    else if (EnigmailMsgRead.checkSignedAttachment(attachment, null, currentAttachments)) {
-      importMenu.setAttribute('disabled', true);
-      decryptOpenMenu.setAttribute('disabled', true);
-      decryptSaveMenu.setAttribute('disabled', true);
-      verifyMenu.removeAttribute('disabled');
-    }
-    else {
-      importMenu.setAttribute('disabled', true);
-      decryptOpenMenu.setAttribute('disabled', true);
-      decryptSaveMenu.setAttribute('disabled', true);
-      verifyMenu.setAttribute('disabled', true);
+    } else if (
+      EnigmailMsgRead.checkSignedAttachment(
+        attachment,
+        null,
+        currentAttachments
+      )
+    ) {
+      importMenu.setAttribute("disabled", true);
+      decryptOpenMenu.setAttribute("disabled", true);
+      decryptSaveMenu.setAttribute("disabled", true);
+      verifyMenu.removeAttribute("disabled");
+    } else {
+      importMenu.setAttribute("disabled", true);
+      decryptOpenMenu.setAttribute("disabled", true);
+      decryptSaveMenu.setAttribute("disabled", true);
+      verifyMenu.setAttribute("disabled", true);
     }
   },
 
-  updateMsgDb: function() {
+  updateMsgDb() {
     EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.updateMsgDb\n");
     var msg = gFolderDisplay.selectedMessage;
-    if (!msg || !msg.folder) return;
+    if (!msg || !msg.folder) {
+      return;
+    }
 
     var msgHdr = msg.folder.GetMessageHeader(msg.messageKey);
 
-    if (this.statusBar.getAttribute("encrypted") == "ok")
-      Enigmail.msg.securityInfo.statusFlags |= EnigmailConstants.DECRYPTION_OKAY;
+    if (this.statusBar.getAttribute("encrypted") == "ok") {
+      Enigmail.msg.securityInfo.statusFlags |=
+        EnigmailConstants.DECRYPTION_OKAY;
+    }
     msgHdr.setUint32Property("enigmail", Enigmail.msg.securityInfo.statusFlags);
   },
 
-  enigCanDetachAttachments: function() {
-    EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: this.enigCanDetachAttachments\n");
+  enigCanDetachAttachments() {
+    EnigmailLog.DEBUG(
+      "enigmailMsgHdrViewOverlay.js: this.enigCanDetachAttachments\n"
+    );
 
     var canDetach = true;
-    if (Enigmail.msg.securityInfo && (typeof(Enigmail.msg.securityInfo.statusFlags) != "undefined")) {
-      canDetach = ((Enigmail.msg.securityInfo.statusFlags &
-        (EnigmailConstants.PGP_MIME_SIGNED | EnigmailConstants.PGP_MIME_ENCRYPTED)) ? false : true);
+    if (
+      Enigmail.msg.securityInfo &&
+      typeof Enigmail.msg.securityInfo.statusFlags != "undefined"
+    ) {
+      canDetach = !(
+        Enigmail.msg.securityInfo.statusFlags &
+        (EnigmailConstants.PGP_MIME_SIGNED |
+          EnigmailConstants.PGP_MIME_ENCRYPTED)
+      );
     }
     return canDetach;
   },
 
-  fillAttachmentListPopup: function(item) {
-    EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: Enigmail.hdrView.fillAttachmentListPopup\n");
+  fillAttachmentListPopup(item) {
+    EnigmailLog.DEBUG(
+      "enigmailMsgHdrViewOverlay.js: Enigmail.hdrView.fillAttachmentListPopup\n"
+    );
     FillAttachmentListPopup(item);
 
     if (!this.enigCanDetachAttachments()) {
       for (var i = 0; i < item.childNodes.length; i++) {
         if (item.childNodes[i].className == "menu-iconic") {
           var mnu = item.childNodes[i].firstChild.firstChild;
           while (mnu) {
-            if (mnu.getAttribute("oncommand").search(/(detachAttachment|deleteAttachment)/) >= 0) {
+            if (
+              mnu
+                .getAttribute("oncommand")
+                .search(/(detachAttachment|deleteAttachment)/) >= 0
+            ) {
               mnu.setAttribute("disabled", true);
             }
             mnu = mnu.nextSibling;
           }
         }
       }
     }
   },
 
-  setSubject: function(subject) {
-    if (gFolderDisplay.selectedMessages.length === 1 && gFolderDisplay.selectedMessage) {
+  setSubject(subject) {
+    if (
+      gFolderDisplay.selectedMessages.length === 1 &&
+      gFolderDisplay.selectedMessage
+    ) {
       let subj = EnigmailData.convertFromUnicode(subject, "utf-8");
-      if (gFolderDisplay.selectedMessage.flags & Components.interfaces.nsMsgMessageFlags.HasRe) {
+      if (gFolderDisplay.selectedMessage.flags & Ci.nsMsgMessageFlags.HasRe) {
         subj = subj.replace(/^(Re: )+(.*)/, "$2");
       }
       gFolderDisplay.selectedMessage.subject = subj;
       this.updateHdrBox("subject", subject); // this needs to be the unmodified subject
 
       let tt = document.getElementById("threadTree");
-      if (tt && ("invalidate" in tt)) {
+      if (tt && "invalidate" in tt) {
         tt.invalidate();
       }
     }
   },
 
-  updateHdrBox: function(header, value) {
+  updateHdrBox(header, value) {
     let e = document.getElementById("expanded" + header + "Box");
     if (e) {
       e.headerValue = value;
     }
   },
 
-  setWindowCallback: function() {
+  setWindowCallback() {
     EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: setWindowCallback\n");
 
     EnigmailSingletons.messageReader = this.headerPane;
   },
 
   headerPane: {
+    isCurrentMessage(uri) {
+      let uriSpec = uri ? uri.spec : null;
 
-    isCurrentMessage: function(uri) {
-      let uriSpec = (uri ? uri.spec : null);
-
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: uri.spec=" + uriSpec + "\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: uri.spec=" +
+          uriSpec +
+          "\n"
+      );
 
       if (!uriSpec || uriSpec.search(/^enigmail:/) === 0) {
         // we cannot compare if no URI given or if URI is Enigmail-internal;
         // therefore assuming it's the current message
         return true;
       }
 
       let msgUriSpec = Enigmail.msg.getCurrentMsgUriSpec();
 
       let currUrl = EnigmailCompat.getUrlFromUriSpec(msgUriSpec);
       if (!currUrl) {
-        EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: could not determine URL\n");
+        EnigmailLog.DEBUG(
+          "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: could not determine URL\n"
+        );
         currUrl = {
           host: "invalid",
           path: "/message",
           scheme: "enigmail",
           spec: "enigmail://invalid/message",
-          schemeIs: function(s) {
+          schemeIs(s) {
             return s === this.scheme;
-          }
+          },
         };
       }
 
       let currMsgId = EnigmailURIs.msgIdentificationFromUrl(currUrl);
       let gotMsgId = EnigmailURIs.msgIdentificationFromUrl(uri);
 
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: url=" + currUrl.spec + "\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: url=" +
+          currUrl.spec +
+          "\n"
+      );
 
-      if (uri.host == currUrl.host &&
+      if (
+        uri.host == currUrl.host &&
         currMsgId.folder === gotMsgId.folder &&
-        currMsgId.msgNum === gotMsgId.msgNum) {
-        EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: true\n");
+        currMsgId.msgNum === gotMsgId.msgNum
+      ) {
+        EnigmailLog.DEBUG(
+          "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: true\n"
+        );
         return true;
       }
 
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: false\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.isCurrentMessage: false\n"
+      );
       return false;
     },
 
     /**
      * Determine if a given MIME part number is a multipart/related message or a child thereof
      *
      * @param mimePart:      Object - The MIME Part object to evaluate from the MIME tree
      * @param searchPartNum: String - The part number to determine
      */
-    isMultipartRelated: function(mimePart, searchPartNum) {
-      if (searchPartNum.indexOf(mimePart.partNum) == 0 && mimePart.partNum.length <= searchPartNum.length) {
-        if (mimePart.fullContentType.search(/^multipart\/related/i) === 0) return true;
+    isMultipartRelated(mimePart, searchPartNum) {
+      if (
+        searchPartNum.indexOf(mimePart.partNum) == 0 &&
+        mimePart.partNum.length <= searchPartNum.length
+      ) {
+        if (mimePart.fullContentType.search(/^multipart\/related/i) === 0) {
+          return true;
+        }
 
         for (let i in mimePart.subParts) {
-          if (this.isMultipartRelated(mimePart.subParts[i], searchPartNum)) return true;
+          if (this.isMultipartRelated(mimePart.subParts[i], searchPartNum)) {
+            return true;
+          }
         }
       }
       return false;
     },
 
     /**
      * Determine if a given mime part number should be displayed.
      * Returns true if one of these conditions is true:
      *  - this is the 1st displayed block of the message
      *  - the message part displayed corresonds to the decrypted part
      *
      * @param mimePartNumber: String - the MIME part number that was decrypted/verified
      * @param uriSpec:        String - the URI spec that is being displayed
      */
-    displaySubPart: function(mimePartNumber, uriSpec) {
-      if ((!mimePartNumber) || (!uriSpec)) return true;
+    displaySubPart(mimePartNumber, uriSpec) {
+      if (!mimePartNumber || !uriSpec) {
+        return true;
+      }
       let part = EnigmailMime.getMimePartNumber(uriSpec);
 
       if (part.length === 0) {
         // only display header if 1st message part
-        if (mimePartNumber.search(/^1(\.1)*$/) < 0) return false;
-      }
-      else {
+        if (mimePartNumber.search(/^1(\.1)*$/) < 0) {
+          return false;
+        }
+      } else {
         let r = EnigmailFuncs.compareMimePartLevel(mimePartNumber, part);
 
         // analyzed mime part is contained in viewed message part
         if (r === 2) {
-          if (mimePartNumber.substr(part.length).search(/^\.1(\.1)*$/) < 0) return false;
+          if (mimePartNumber.substr(part.length).search(/^\.1(\.1)*$/) < 0) {
+            return false;
+          }
+        } else if (r !== 0) {
+          return false;
         }
-        else if (r !== 0) return false;
 
         if (Enigmail.msg.mimeParts) {
-          if (this.isMultipartRelated(Enigmail.msg.mimeParts, mimePartNumber)) return false;
+          if (this.isMultipartRelated(Enigmail.msg.mimeParts, mimePartNumber)) {
+            return false;
+          }
         }
       }
       return true;
     },
 
     /**
      * Determine if there are message parts that are not signed/encrypted
      *
      * @param mimePartNumber String - the MIME part number that was authenticated
      *
      * @return Boolean: true: there are siblings / false: no siblings
      */
-    hasUnauthenticatedParts: function(mimePartNumber) {
+    hasUnauthenticatedParts(mimePartNumber) {
       function hasSiblings(mimePart, searchPartNum, parentNum) {
         if (mimePart.partNum === parentNum) {
           // if we're a direct child of a PGP/MIME encrypted message, we know that everything
           // is authenticated on this level
-          if (mimePart.fullContentType.search(/^multipart\/encrypted.{1,255}protocol="?application\/pgp-encrypted"?/i) === 0) return false;
+          if (
+            mimePart.fullContentType.search(
+              /^multipart\/encrypted.{1,255}protocol="?application\/pgp-encrypted"?/i
+            ) === 0
+          ) {
+            return false;
+          }
         }
-        if (mimePart.partNum.indexOf(parentNum) == 0 && mimePart.partNum !== searchPartNum) return true;
+        if (
+          mimePart.partNum.indexOf(parentNum) == 0 &&
+          mimePart.partNum !== searchPartNum
+        ) {
+          return true;
+        }
 
         for (let i in mimePart.subParts) {
-          if (hasSiblings(mimePart.subParts[i], searchPartNum, parentNum)) return true;
+          if (hasSiblings(mimePart.subParts[i], searchPartNum, parentNum)) {
+            return true;
+          }
         }
 
         return false;
       }
 
       let parentNum = mimePartNumber.replace(/\.\d+$/, "");
       if (mimePartNumber.search(/\./) < 0) {
         parentNum = "";
       }
 
       if (mimePartNumber && Enigmail.msg.mimeParts) {
-        if (hasSiblings(Enigmail.msg.mimeParts, mimePartNumber, parentNum)) return true;
+        if (hasSiblings(Enigmail.msg.mimeParts, mimePartNumber, parentNum)) {
+          return true;
+        }
       }
 
       return false;
     },
 
-    updateSecurityStatus: function(unusedUriSpec, exitCode, statusFlags, keyId, userId, sigDetails, errorMsg, blockSeparation, uri, extraDetails, mimePartNumber) {
+    updateSecurityStatus(
+      unusedUriSpec,
+      exitCode,
+      statusFlags,
+      keyId,
+      userId,
+      sigDetails,
+      errorMsg,
+      blockSeparation,
+      uri,
+      extraDetails,
+      mimePartNumber
+    ) {
       // uriSpec is not used for Enigmail anymore. It is here becaue other addons and pEp rely on it
 
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: updateSecurityStatus: mimePart=" + mimePartNumber + "\n");
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: updateSecurityStatus: mimePart=" +
+          mimePartNumber +
+          "\n"
+      );
 
-
-      let uriSpec = (uri ? uri.spec : null);
+      let uriSpec = uri ? uri.spec : null;
 
       if (this.isCurrentMessage(uri)) {
-
         if (statusFlags & EnigmailConstants.DECRYPTION_OKAY) {
           if (gEncryptedURIService) {
             // remember encrypted message URI to enable TB prevention against EFAIL attack
-            Enigmail.hdrView.lastEncryptedUri = gFolderDisplay.selectedMessageUris[0];
-            gEncryptedURIService.rememberEncrypted(Enigmail.hdrView.lastEncryptedUri);
+            Enigmail.hdrView.lastEncryptedUri =
+              gFolderDisplay.selectedMessageUris[0];
+            gEncryptedURIService.rememberEncrypted(
+              Enigmail.hdrView.lastEncryptedUri
+            );
           }
         }
 
-        if (!this.displaySubPart(mimePartNumber, uriSpec)) return;
+        if (!this.displaySubPart(mimePartNumber, uriSpec)) {
+          return;
+        }
         if (this.hasUnauthenticatedParts(mimePartNumber)) {
-          EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: updateSecurityStatus: found unauthenticated part\n");
+          EnigmailLog.DEBUG(
+            "enigmailMsgHdrViewOverlay.js: updateSecurityStatus: found unauthenticated part\n"
+          );
           statusFlags |= EnigmailConstants.PARTIALLY_PGP;
         }
 
         let encToDetails = "";
         if (extraDetails && extraDetails.length > 0) {
           try {
             let o = JSON.parse(extraDetails);
             if ("encryptedTo" in o) {
               encToDetails = o.encryptedTo;
             }
-          }
-          catch (x) {}
+          } catch (x) {}
         }
 
-        Enigmail.hdrView.updateHdrIcons(exitCode, statusFlags, keyId, userId, sigDetails,
-          errorMsg, blockSeparation, encToDetails,
-          null, mimePartNumber);
+        Enigmail.hdrView.updateHdrIcons(
+          exitCode,
+          statusFlags,
+          keyId,
+          userId,
+          sigDetails,
+          errorMsg,
+          blockSeparation,
+          encToDetails,
+          null,
+          mimePartNumber
+        );
       }
 
       if (uriSpec && uriSpec.search(/^enigmail:message\//) === 0) {
         // display header for broken MS-Exchange message
         // Thunderbird
         let ebeb = document.getElementById("enigmailBrokenExchangeBox");
         ebeb.removeAttribute("collapsed");
       }
-
-      return;
     },
 
-    processDecryptionResult: function(uri, actionType, processData, mimePartNumber) {
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.processDecryptionResult:\n");
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: actionType= " + actionType + ", mimePart=" + mimePartNumber + "\n");
+    processDecryptionResult(uri, actionType, processData, mimePartNumber) {
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.processDecryptionResult:\n"
+      );
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: actionType= " +
+          actionType +
+          ", mimePart=" +
+          mimePartNumber +
+          "\n"
+      );
 
       let msg = gFolderDisplay.selectedMessage;
-      if (!msg) return;
-      if (!this.isCurrentMessage(uri) || gFolderDisplay.selectedMessages.length !== 1) return;
+      if (!msg) {
+        return;
+      }
+      if (
+        !this.isCurrentMessage(uri) ||
+        gFolderDisplay.selectedMessages.length !== 1
+      ) {
+        return;
+      }
 
       switch (actionType) {
         case "modifyMessageHeaders":
           this.modifyMessageHeaders(uri, processData, mimePartNumber);
           return;
         case "wksConfirmRequest":
           Enigmail.hdrView.checkWksConfirmRequest(processData);
-          return;
       }
     },
 
-    modifyMessageHeaders: function(uri, headerData, mimePartNumber) {
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.modifyMessageHeaders:\n");
+    modifyMessageHeaders(uri, headerData, mimePartNumber) {
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.modifyMessageHeaders:\n"
+      );
 
-      let updateHdrBox = Enigmail.hdrView.updateHdrBox;
-      let uriSpec = (uri ? uri.spec : null);
+      let uriSpec = uri ? uri.spec : null;
       let hdr;
 
       try {
         hdr = JSON.parse(headerData);
-      }
-      catch (ex) {
-        EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: modifyMessageHeaders: - no headers to display\n");
+      } catch (ex) {
+        EnigmailLog.DEBUG(
+          "enigmailMsgHdrViewOverlay.js: modifyMessageHeaders: - no headers to display\n"
+        );
         return;
       }
 
-      if (typeof(hdr) !== "object") return;
-      if (!this.displaySubPart(mimePartNumber, uriSpec)) return;
+      if (typeof hdr !== "object") {
+        return;
+      }
+      if (!this.displaySubPart(mimePartNumber, uriSpec)) {
+        return;
+      }
 
       let msg = gFolderDisplay.selectedMessage;
 
       if ("subject" in hdr) {
         Enigmail.hdrView.setSubject(hdr.subject);
       }
 
       if ("date" in hdr) {
@@ -1336,71 +1744,104 @@ Enigmail.hdrView = {
 
             if ("reply-to" in hdr) {
               gExpandedHeaderView["reply-to"].outputFunction(gExpandedHeaderView["reply-to"], hdr["reply-to"]);
               msg.setStringProperty("Enigmail-ReplyTo", hdr["reply-to"]);
             }
       */
     },
 
-    handleSMimeMessage: function(uri) {
+    handleSMimeMessage(uri) {
       if (this.isCurrentMessage(uri)) {
         EnigmailVerify.unregisterContentTypeHandler();
         Enigmail.msg.messageReload(false);
       }
     },
 
-    maxWantedNesting: function() {
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.maxWantedNesting:\n");
+    maxWantedNesting() {
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.maxWantedNesting:\n"
+      );
       return this._smimeHeaderSink.maxWantedNesting();
     },
 
-    signedStatus: function(aNestingLevel, aSignatureStatus, aSignerCert) {
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.signedStatus:\n");
-      return this._smimeHeaderSink.signedStatus(aNestingLevel, aSignatureStatus, aSignerCert);
+    signedStatus(aNestingLevel, aSignatureStatus, aSignerCert) {
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.signedStatus:\n"
+      );
+      return this._smimeHeaderSink.signedStatus(
+        aNestingLevel,
+        aSignatureStatus,
+        aSignerCert
+      );
     },
 
-    encryptionStatus: function(aNestingLevel, aEncryptionStatus, aRecipientCert) {
-      EnigmailLog.DEBUG("enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.encryptionStatus:\n");
-      return this._smimeHeaderSink.encryptionStatus(aNestingLevel, aEncryptionStatus, aRecipientCert);
-    }
+    encryptionStatus(aNestingLevel, aEncryptionStatus, aRecipientCert) {
+      EnigmailLog.DEBUG(
+        "enigmailMsgHdrViewOverlay.js: EnigMimeHeaderSink.encryptionStatus:\n"
+      );
+      return this._smimeHeaderSink.encryptionStatus(
+        aNestingLevel,
+        aEncryptionStatus,
+        aRecipientCert
+      );
+    },
   },
 
-  onUnloadEnigmail: function() {
-    window.removeEventListener("load-enigmail", Enigmail.hdrView.hdrViewLoad, false);
+  onUnloadEnigmail() {
+    window.removeEventListener("load-enigmail", Enigmail.hdrView.hdrViewLoad);
     for (let i = 0; i < gMessageListeners.length; i++) {
       if (gMessageListeners[i] === Enigmail.hdrView.messageListener) {
         gMessageListeners.splice(i, 1);
         break;
       }
     }
 
     let signedHdrElement = document.getElementById("signedHdrIcon");
     if (signedHdrElement) {
-      signedHdrElement.setAttribute("onclick", "showMessageReadSecurityInfo();");
+      signedHdrElement.setAttribute(
+        "onclick",
+        "showMessageReadSecurityInfo();"
+      );
     }
 
     let encryptedHdrElement = document.getElementById("encryptedHdrIcon");
     if (encryptedHdrElement) {
-      encryptedHdrElement.setAttribute("onclick", "showMessageReadSecurityInfo();");
+      encryptedHdrElement.setAttribute(
+        "onclick",
+        "showMessageReadSecurityInfo();"
+      );
     }
 
     let addrPopup = document.getElementById("emailAddressPopup");
     if (addrPopup) {
-      addrPopup.removeEventListener("popupshowing", Enigmail.hdrView.displayAddressPopup, false);
+      addrPopup.removeEventListener(
+        "popupshowing",
+        Enigmail.hdrView.displayAddressPopup
+      );
     }
 
     let attCtx = document.getElementById("attachmentItemContext");
     if (attCtx) {
-      attCtx.removeEventListener("popupshowing", this.onShowAttachmentContextMenu, false);
+      attCtx.removeEventListener(
+        "popupshowing",
+        this.onShowAttachmentContextMenu
+      );
     }
 
     let msgFrame = EnigmailWindows.getFrame(window, "messagepane");
     if (msgFrame) {
-      msgFrame.removeEventListener("unload", Enigmail.hdrView.messageUnload, true);
-      msgFrame.removeEventListener("load", Enigmail.hdrView.messageLoad, false);
+      msgFrame.removeEventListener(
+        "unload",
+        Enigmail.hdrView.messageUnload,
+        true
+      );
+      msgFrame.removeEventListener("load", Enigmail.hdrView.messageLoad);
     }
 
     CanDetachAttachments = Enigmail.hdrView.origCanDetachAttachments;
-  }
+  },
 };
 
-window.addEventListener("load-enigmail", Enigmail.hdrView.hdrViewLoad.bind(Enigmail.hdrView), false);
+window.addEventListener(
+  "load-enigmail",
+  Enigmail.hdrView.hdrViewLoad.bind(Enigmail.hdrView)
+);
--- a/mail/extensions/openpgp/content/ui/keyDetailsDlg.js
+++ b/mail/extensions/openpgp/content/ui/keyDetailsDlg.js
@@ -1,31 +1,29 @@
 /*
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  */
 
-
 /* global EnigmailLog: false, EnigmailLocale: false, EnigmailKey: false, EnigmailKeyRing: false */
 
 // from enigmailCommon.js:
 /* global GetEnigmailSvc: false, EnigAlert: false, EnigConvertGpgToUnicode: false */
 /* global EnigCleanGuiList: false, EnigGetTrustLabel: false, EnigShowPhoto: false, EnigSignKey: false */
 /* global EnigEditKeyExpiry: false, EnigEditKeyTrust: false, EnigChangeKeyPwd: false, EnigRevokeKey: false */
 /* global EnigCreateRevokeCert: false, EnigmailTimer: false */
 
 // from enigmailKeyManager.js:
 /* global keyMgrAddPhoto: false, EnigmailCompat: false */
 
 "use strict";
 
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+  .Services;
 
 var gKeyId = null;
 var gUserId = null;
 var gKeyList = null;
 var gTreeFuncs = null;
 
 function onLoad() {
   window.arguments[1].refresh = false;
@@ -56,62 +54,56 @@ function setLabel(elementId, label) {
 
 function reloadData() {
   var enigmailSvc = GetEnigmailSvc();
   if (!enigmailSvc) {
     EnigAlert(EnigmailLocale.getString("accessError"));
     window.close();
     return;
   }
-  var exitCodeObj = {};
-  var statusFlagsObj = {};
-  var errorMsgObj = {};
 
   gUserId = null;
 
-  var fingerprint = "";
-  var subKeyLen = "";
-  var subAlgo = "";
   var treeChildren = document.getElementById("keyListChildren");
   var uidList = document.getElementById("additionalUid");
   var photoImg = document.getElementById("photoIdImg");
 
   // clean lists
   EnigCleanGuiList(treeChildren);
   EnigCleanGuiList(uidList);
 
   let keyObj = EnigmailKeyRing.getKeyById(gKeyId);
   if (keyObj) {
-
     if (keyObj.secretAvailable) {
       setLabel("keyType", EnigmailLocale.getString("keyTypePair"));
       document.getElementById("ownKeyCommands").removeAttribute("hidden");
     } else {
       document.getElementById("ownKeyCommands").setAttribute("hidden", "true");
       setLabel("keyType", EnigmailLocale.getString("keyTypePublic"));
     }
 
     if (keyObj.photoAvailable === true) {
       let pFile = keyObj.getPhotoFile(0);
 
       if (pFile && pFile.isFile() && pFile.isReadable()) {
-        const photoUri = Cc["@mozilla.org/network/io-service;1"].
-        getService(Ci.nsIIOService).newFileURI(pFile).spec;
+        const photoUri = Services.io.newFileURI(pFile).spec;
 
         photoImg.setAttribute("src", photoUri);
         photoImg.removeAttribute("hidden");
       }
     } else {
       photoImg.setAttribute("hidden", "true");
     }
 
     if (keyObj.isOwnerTrustUseful()) {
       document.getElementById("setOwnerTrust").removeAttribute("collapsed");
     } else {
-      document.getElementById("setOwnerTrust").setAttribute("collapsed", "true");
+      document
+        .getElementById("setOwnerTrust")
+        .setAttribute("collapsed", "true");
     }
 
     if (keyObj.hasSubUserIds()) {
       document.getElementById("alsoknown").removeAttribute("collapsed");
       createUidData(uidList, keyObj);
     } else {
       document.getElementById("alsoknown").setAttribute("collapsed", "true");
     }
@@ -137,17 +129,16 @@ function reloadData() {
     setText("keyCreated", keyObj.created);
     setText("keyExpiry", expiryDate);
     if (keyObj.fpr) {
       setLabel("fingerprint", EnigmailKey.formatFpr(keyObj.fpr));
     }
   }
 }
 
-
 function createUidData(listNode, keyDetails) {
   for (let i = 1; i < keyDetails.userIds.length; i++) {
     if (keyDetails.userIds[i].type === "uid") {
       let item = listNode.appendItem(keyDetails.userIds[i].userId);
       item.setAttribute("label", keyDetails.userIds[i].userId);
       if ("dre".search(keyDetails.userIds[i].keyTrust) >= 0) {
         item.setAttribute("class", "enigmailDisabled");
       }
@@ -186,252 +177,254 @@ function keyDetailsAddPhoto() {
 
 function signKey() {
   if (EnigSignKey(gUserId, gKeyId, null)) {
     enableRefresh();
     reloadData();
   }
 }
 
-
 function changeExpirationDate() {
   if (EnigEditKeyExpiry([gUserId], [gKeyId])) {
     enableRefresh();
     reloadData();
   }
 }
 
-
 function setOwnerTrust() {
-
   if (EnigEditKeyTrust([gUserId], [gKeyId])) {
     enableRefresh();
     reloadData();
   }
 }
 
 function manageUids() {
   let keyObj = EnigmailKeyRing.getKeyById(gKeyId);
 
   var inputObj = {
     keyId: keyObj.keyId,
-    ownKey: keyObj.secretAvailable
+    ownKey: keyObj.secretAvailable,
   };
 
   var resultObj = {
-    refresh: false
+    refresh: false,
   };
-  window.openDialog("chrome://openpgp/content/ui/enigmailManageUidDlg.xhtml",
-    "", "dialog,modal,centerscreen,resizable=yes", inputObj, resultObj);
+  window.openDialog(
+    "chrome://openpgp/content/ui/enigmailManageUidDlg.xhtml",
+    "",
+    "dialog,modal,centerscreen,resizable=yes",
+    inputObj,
+    resultObj
+  );
   if (resultObj.refresh) {
     enableRefresh();
     reloadData();
   }
 }
 
 function changePassword() {
   EnigChangeKeyPwd(gKeyId, gUserId);
 }
 
 function revokeKey() {
-  EnigRevokeKey(gKeyId, gUserId, function _revokeKeyCb(success) {
+  EnigRevokeKey(gKeyId, gUserId, function(success) {
     if (success) {
       enableRefresh();
       reloadData();
     }
   });
 }
 
 function genRevocationCert() {
   EnigCreateRevokeCert(gKeyId, gUserId);
 }
 
-
 function SigListView(keyObj) {
   this.keyObj = [];
 
   let sigObj = keyObj.signatures;
   for (let i in sigObj) {
     let k = {
       uid: sigObj[i].userId,
       fpr: sigObj[i].fpr,
       created: sigObj[i].created,
       expanded: true,
-      sigList: []
+      sigList: [],
     };
 
     for (let j in sigObj[i].sigList) {
       let s = sigObj[i].sigList[j];
       if (s.sigKnown) {
         let sig = EnigmailKeyRing.getKeyById(s.signerKeyId);
         k.sigList.push({
           uid: s.userId,
           created: s.created,
           fpr: sig ? sig.fpr : "",
-          sigType: s.sigType
+          sigType: s.sigType,
         });
       }
     }
     this.keyObj.push(k);
   }
 
   this.prevKeyObj = null;
   this.prevRow = -1;
 
   this.updateRowCount();
 }
 
 // implements nsITreeView
 SigListView.prototype = {
-
-  updateRowCount: function() {
+  updateRowCount() {
     let rc = 0;
 
     for (let i in this.keyObj) {
       rc += this.keyObj[i].expanded ? this.keyObj[i].sigList.length + 1 : 1;
     }
 
     this.rowCount = rc;
   },
 
-  setLastKeyObj: function(keyObj, row) {
+  setLastKeyObj(keyObj, row) {
     this.prevKeyObj = keyObj;
     this.prevRow = row;
     return keyObj;
   },
 
-  getSigAtIndex: function(row) {
+  getSigAtIndex(row) {
     if (this.lastIndex == row) {
       return this.lastKeyObj;
     }
 
     let j = 0,
       l = 0;
 
     for (let i in this.keyObj) {
-      if (j === row) return this.setLastKeyObj(this.keyObj[i], row);
+      if (j === row) {
+        return this.setLastKeyObj(this.keyObj[i], row);
+      }
       j++;
 
       if (this.keyObj[i].expanded) {
         l = this.keyObj[i].sigList.length;
 
         if (j + l >= row && row - j < l) {
           return this.setLastKeyObj(this.keyObj[i].sigList[row - j], row);
-        } else {
-          j += l;
         }
+        j += l;
       }
     }
 
     return null;
   },
 
-  getCellText: function(row, column) {
+  getCellText(row, column) {
     let s = this.getSigAtIndex(row);
 
     if (s) {
       switch (column.id) {
         case "sig_uid_col":
           return s.uid;
         case "sig_fingerprint_col":
           return EnigmailKey.formatFpr(s.fpr);
         case "sig_created_col":
           return s.created;
       }
     }
 
     return "";
   },
 
-  setTree: function(treebox) {
+  setTree(treebox) {
     this.treebox = treebox;
   },
 
-  isContainer: function(row) {
+  isContainer(row) {
     let s = this.getSigAtIndex(row);
-    return ("sigList" in s);
+    return "sigList" in s;
   },
 
-  isSeparator: function(row) {
+  isSeparator(row) {
     return false;
   },
 
-  isSorted: function() {
+  isSorted() {
     return false;
   },
 
-  getLevel: function(row) {
+  getLevel(row) {
     let s = this.getSigAtIndex(row);
-    return ("sigList" in s ? 0 : 1);
+    return "sigList" in s ? 0 : 1;
   },
 
-  cycleHeader: function(col, elem) {},
+  cycleHeader(col, elem) {},
 
-  getImageSrc: function(row, col) {
+  getImageSrc(row, col) {
     return null;
   },
 
-  getRowProperties: function(row, props) {},
+  getRowProperties(row, props) {},
 
-  getCellProperties: function(row, col) {
+  getCellProperties(row, col) {
     if (col.id === "sig_fingerprint_col") {
       return "fixedWidthFont";
     }
 
     return "";
   },
 
-  canDrop: function(row, orientation, data) {
+  canDrop(row, orientation, data) {
     return false;
   },
 
-  getColumnProperties: function(colid, col, props) {},
+  getColumnProperties(colid, col, props) {},
 
-  isContainerEmpty: function(row) {
+  isContainerEmpty(row) {
     return false;
   },
 
-  getParentIndex: function(idx) {
+  getParentIndex(idx) {
     return -1;
   },
 
-  getProgressMode: function(row, col) {},
+  getProgressMode(row, col) {},
 
-  isContainerOpen: function(row) {
+  isContainerOpen(row) {
     let s = this.getSigAtIndex(row);
     return s.expanded;
   },
 
-  isSelectable: function(row, col) {
+  isSelectable(row, col) {
     return true;
   },
 
-  toggleOpenState: function(row) {
+  toggleOpenState(row) {
     let s = this.getSigAtIndex(row);
     s.expanded = !s.expanded;
     let r = this.rowCount;
     this.updateRowCount();
     gTreeFuncs.rowCountChanged(row, this.rowCount - r);
-  }
+  },
 };
 
 function createSubkeyItem(subkey) {
-
   // Get expiry state of this subkey
   let expire;
   if (subkey.keyTrust === "r") {
     expire = EnigmailLocale.getString("keyValid.revoked");
   } else if (subkey.expiryTime === 0) {
     expire = EnigmailLocale.getString("keyExpiryNever");
   } else {
     expire = subkey.expiry;
   }
 
-  let subkeyType = subkey.type === "pub" ? EnigmailLocale.getString("keyTypePrimary") :
-    EnigmailLocale.getString("keyTypeSubkey");
+  let subkeyType =
+    subkey.type === "pub"
+      ? EnigmailLocale.getString("keyTypePrimary")
+      : EnigmailLocale.getString("keyTypeSubkey");
 
   let usagetext = "";
   let i;
   //  e = encrypt
   //  s = sign
   //  c = certify
   //  a = authentication
   //  Capital Letters are ignored, as these reflect summary properties of a key
@@ -457,49 +450,48 @@ function createSubkeyItem(subkey) {
           usagetext = usagetext + ", ";
         }
         usagetext = usagetext + EnigmailLocale.getString("keyUsageCertify");
         break;
       case "a":
         if (usagetext.length > 0) {
           usagetext = usagetext + ", ";
         }
-        usagetext = usagetext + EnigmailLocale.getString("keyUsageAuthentication");
+        usagetext =
+          usagetext + EnigmailLocale.getString("keyUsageAuthentication");
         break;
     } // * case *
   } // * for *
 
   let keyObj = {
     keyType: subkeyType,
     keyId: "0x" + subkey.keyId,
     algo: subkey.algoSym,
     size: subkey.keySize,
     creationDate: subkey.created,
     expiry: expire,
-    usage: usagetext
+    usage: usagetext,
   };
 
   return keyObj;
 }
 
 function SubkeyListView(keyObj) {
   this.subkeys = [];
   this.rowCount = keyObj.subKeys.length + 1;
   this.subkeys.push(createSubkeyItem(keyObj));
 
   for (let i = 0; i < keyObj.subKeys.length; i++) {
     this.subkeys.push(createSubkeyItem(keyObj.subKeys[i]));
   }
-
 }
 
 // implements nsITreeView
 SubkeyListView.prototype = {
-
-  getCellText: function(row, column) {
+  getCellText(row, column) {
     let s = this.subkeys[row];
 
     if (s) {
       switch (column.id) {
         case "keyTypeCol":
           return s.keyType;
         case "keyIdCol":
           return s.keyId;
@@ -514,66 +506,66 @@ SubkeyListView.prototype = {
         case "keyUsageCol":
           return s.usage;
       }
     }
 
     return "";
   },
 
-  setTree: function(treebox) {
+  setTree(treebox) {
     this.treebox = treebox;
   },
 
-  isContainer: function(row) {
+  isContainer(row) {
     return false;
   },
 
-  isSeparator: function(row) {
+  isSeparator(row) {
     return false;
   },
 
-  isSorted: function() {
+  isSorted() {
     return false;
   },
 
-  getLevel: function(row) {
+  getLevel(row) {
     return 0;
   },
 
-  cycleHeader: function(col, elem) {},
+  cycleHeader(col, elem) {},
 
-  getImageSrc: function(row, col) {
+  getImageSrc(row, col) {
     return null;
   },
 
-  getRowProperties: function(row, props) {},
+  getRowProperties(row, props) {},
 
-  getCellProperties: function(row, col) {
+  getCellProperties(row, col) {
     return "";
   },
 
-  canDrop: function(row, orientation, data) {
+  canDrop(row, orientation, data) {
     return false;
   },
 
-  getColumnProperties: function(colid, col, props) {},
+  getColumnProperties(colid, col, props) {},
 
-  isContainerEmpty: function(row) {
+  isContainerEmpty(row) {
     return false;
   },
 
-  getParentIndex: function(idx) {
+  getParentIndex(idx) {
     return -1;
   },
 
-  getProgressMode: function(row, col) {},
+  getProgressMode(row, col) {},
 
-  isContainerOpen: function(row) {
+  isContainerOpen(row) {
     return false;
   },
 
-  isSelectable: function(row, col) {
+  isSelectable(row, col) {
     return true;
   },
 
-  toggleOpenState: function(row) {}
+  toggleOpenState(row) {},
 };